Why can't my javascript code in the head selection get an element?

前端 未结 3 595
醉梦人生
醉梦人生 2021-01-21 16:20

I have been working on a pi calculator in javascript for a long time now and I have finally finished. The problem is that my script in the head section:

document         


        
3条回答
  •  清酒与你
    2021-01-21 16:48

    Wrap it on a window onload event:

    window.onload = function()
    {
        document.getElementById("button").addEventListener('click', (function(){
            alert('Beginning…');
        }), false);
    };
    

    or

    window.addEventListener('load', function()
    {
        document.getElementById("button").addEventListener('click', (function(){
            alert('Beginning…');
        }), false);
    });
    

    or, if your script doesn't have to be in the head, put it after the element that has the id of button.

    DEMO

提交回复
热议问题