Javascript: Functions get called on page load instead of onclick/onsubmit

北城余情 提交于 2019-11-30 20:50:42

That's not right, it should be:

function init(){
    document.getElementById("test").onclick = function () { alert("hello"); };
}

This is because you need in JavaScript you need to assign the function itself to the click event (alert is a function).

Take this for example:

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

document.getElementById("test").onclick = hello;

Note that I didn't put the brackets () after hello function? That's because I'm using a reference to the function itself. If I put the brackets, I'm actually evaluating that function at the point in time of the click assignment happening.

So doing:

document.getElementById("test").onclick = hello();

Will show the alert will show the alert immediately after this line has been executed.

yes your javascript function will call only when page will load .If you also want to call that init() function on click Test button so please try like this :

JavaScript:

function init(){ alert("hello"); }

window.onload = init;
HTML: 
<button id="test" onClick='init()'>Test</button>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!