Onclick of a button run a function - not working?

2020-04-19 04:52发布

问题:

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!

回答1:

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.



回答2:

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.



回答3:

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;


回答4:

You can do

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

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

or

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


回答5:

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

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