TypeError is Null?

前端 未结 4 550
我在风中等你
我在风中等你 2021-01-12 01:29

This is an error in Firebug I keep seeing.

TypeError: $(\"#gallery-nav-button\") is null
 [Break On This Error]  
$(\'#gallery-nav-button\').addClass(\'anima         


        
4条回答
  •  礼貌的吻别
    2021-01-12 02:12

    I also want to add - because this is the #1 Google search result for the important error message "TypeError: [x] is null" - that the most common reason a JavaScript developer will get this is that they are trying to assign an event handler to a DOM element, but the DOM element hasn't been created yet.

    Code is basically run from top to bottom. Most devs put their JavaScript in the head of their HTML file. The browser has received the HTML, CSS and JavaScript from the server; is "executing"/rendering the Web page; and is executing the JavaScript, but it hasn't gotten further down the HTML file to "execute"/render the HTML.

    To handle this, you need to introduce a delay before your JavaScript is executed, like putting it inside a function that isn't called until the browser has "executed" all of the HTML and fires the event "DOM ready."

    With raw JavaScript, use window.onload:

    window.onload=function() {
       /*your code here*
       /*var date = document.getElementById("date");
       /*alert(date);
    }
    

    With jQuery, use document ready:

    $(document).ready(function() {
       /*your code here*
       /*var date = document.getElementById("date");
       /*alert(date);
    });
    

    This way, your JavaScript won't run until the browser has built the DOM, the HTML element exists (not null :-) ) and your JavaScript can find it and attach an event handler to it.

提交回复
热议问题