Onclick() function on working

后端 未结 4 1100
名媛妹妹
名媛妹妹 2020-12-22 13:40

all! I am having a problem using the a simple onclick method. Kindly please help me out. Here is that code... When i click on the button nothing really happens.



        
4条回答
  •  长情又很酷
    2020-12-22 14:00

    window.onload=initall();
    

    calls the function initall and assigns the return value of initall as event handler. That is, initall is executed immediately and not when the load event is triggered.
    Similar for btn.onclick=alert('hi');. But in both cases, the return value is not a function.

    You have to assign functions to those properties, which are then being called when the event occurs.

    function initall(){
        var btn = document.getElementById('btn');
    
        btn.onclick = function() { // creates and assigns the function at once
            alert('hi');
        };
    }
    
    window.onload = initall; // assign the function reference, no `()`.
    

    I recommend to read the excellent tutorials at quirksmode.org to learn about event handling and of course the MDN JavaScript Guide for the JavaScript basics.

提交回复
热议问题