Onclick of a button run a function - not working?

白昼怎懂夜的黑 提交于 2019-12-02 04:53:43

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.

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.

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;

You can do

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

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

or

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

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

document.getElementById("go-btn").onclick = function() {hi()};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!