Onclick of a button run a function - not working?

2020-04-19 05:24发布

html:

<button id="go-btn">GO BUTTON!</button>

javascript:

function hi(){
    alert("hi");
}

document.getElementById("go-btn").onclick = hi();

When I refresh the page the alert pops up before I click the button. Why is this happening? Thanks a lot!

5条回答
我只想做你的唯一
2楼-- · 2020-04-19 05:28

Because you are calling it while the assignment:

document.getElementById("go-btn").onclick = hi();

Just remove the () and you assign the hi-function to the onclick-handler.

document.getElementById("go-btn").onclick = hi;

Currently you are assigning the RESULT of hi() to the onclick-handler.

查看更多
对你真心纯属浪费
3楼-- · 2020-04-19 05:28

You can do

var hi = function(){
    alert("hi");
}

document.getElementById("go-btn").onclick = hi();

or

document.getElementById("go-btn").onclick = hi;
查看更多
不美不萌又怎样
4楼-- · 2020-04-19 05:32

You need to say:

document.getElementById("go-btn").onclick = function(){hi();}

Otherwise it will call the hi() function other than setting it onclick.

Another way to do this is:

document.getElementById("go-btn").onclick = hi;
查看更多
Animai°情兽
5楼-- · 2020-04-19 05:33

You need to put your function call hi() into an anonymous function :

document.getElementById("go-btn").onclick = function() {hi()};
查看更多
Anthone
6楼-- · 2020-04-19 05:43

Try this:

function hi(){
    alert("hi");
}

document.getElementById("go-btn").onclick = hi;

Notice how I removed the () from the assignment. You were calling the function immediately on load.

查看更多
登录 后发表回答