Does this code need to be in a document.ready?

前端 未结 7 2116
清酒与你
清酒与你 2020-12-28 13:09

The document.ready is used to execute code after the DOM is fully loaded. This can be used to attach event handlers to elements on the page e.g



        
7条回答
  •  旧巷少年郎
    2020-12-28 13:57

    In addition to the answers: you can mere use jquery live function (instead of keydown, etc.) to be free of the situation 'DOM elements must be finished'.

    So the next must work properly:

    $( "#somediv" ).live( 'keydown', function(){ ... } );
    

    In this case jQuery binds the event when it is possible. You don't have a pain to place all bindings in one (ready) function, your bindings can be placed in independent parts of your HTML page or Javascript files.

    So, the result answer is: no, you don't need to place your code in document.ready when you use the mentioned function.

    Update

    In the last versions of jQuery (>= 1.7) use on() function instead of live() because the last one is depricated. So, it's not necessary to place event bindings into ready().

提交回复
热议问题