Onclick of a button run a function - not working?

天大地大妈咪最大 提交于 2019-12-02 09:07:43

问题


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()};


来源:https://stackoverflow.com/questions/26783476/onclick-of-a-button-run-a-function-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!