[removed] Functions get called on page load instead of onclick/onsubmit

前端 未结 2 893
独厮守ぢ
独厮守ぢ 2021-01-05 16:14

I\'m relatively new to JS, but I have programmed in C before, and I\'m trying to get my head around the whole event driven nature of it. I\'m trying to create a script that

相关标签:
2条回答
  • 2021-01-05 16:38

    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>

    0 讨论(0)
  • 2021-01-05 16:46

    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.

    0 讨论(0)
提交回复
热议问题