Why should $.click() be enclosed within $(document).ready()?

前端 未结 5 792
盖世英雄少女心
盖世英雄少女心 2020-12-03 17:34

I am going through http://docs.jquery.com/How_jQuery_Works and find the requirement of enclosing $.click() event in $(document).ready() even a litt

5条回答
  •  情书的邮戳
    2020-12-03 17:53

    It's not the actual call to .click() which is the concern here, but rather the selector for the element on which it's called.

    For example, if there is an element with id="myButton" then you would reference it with:

    $('#myButton')
    

    However, if that element isn't yet loaded (that is, if the document isn't yet ready and you don't know what elements are currently loaded), then that selector won't find anything. So it won't call .click() on anything (either to bind the event or to fire it, depending on the argument(s) to .click()).

    You can use other approaches, such as the jQuery .on() function, which can bind events to common parent elements and filter "bubbled up" events from ones added later later in the life of the document. But if you're just using a normal selector and calling a function then the selector needs to find something within the DOM in order for the function to do anything.

提交回复
热议问题