简体   繁体   中英

JQuery explanation on document.ready

I have question will the click event or any other event run in document.ready() for the first time? I mean will it reach after loading DOM elements to the comment without clicking first time? :)

$(document).ready(
  $(#foo).click( 
   function()
    {
       // "It reached here after DOM is loaded!"
    }
  )
)

document.ready fires when the DOM is fully loaded, so you would be correct.

The 'click' event, however, will not fire unless the bound element is clicked or the click event is explicitly called using click() or Events/trigger :

$('#foo').click();
$('#foo').trigger("click");

Have you read the manual page for document.ready? See:

http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

No, the function will not be executed.

There are a few errors:

$(document).ready() takes a function as an argument. '#foo' should also be a string.

$(document).ready(function() {
  $('#foo').click( 
   function()
    {
       // "It reached here after DOM is loaded!"
    }
  )
})

If you want the function to be evaluated at least once, after the dom loads. Then probably the easiest way is to name your function.

eg:

$(document).ready(function() {
  $('#foo').click( 
   function myfunction()
    {
       // "It reached here after DOM is loaded!"
    }
  );
  myfunction();
})

If you need the function to execute in the scope of $('#foo') you can do so with Function.call() method.

eg:

$(document).ready(function() {
  $('#foo').click( 
   function myfunction()
    {
       // "It reached here after DOM is loaded!"
    }
  );
  myfunction.call($('foo'));
})

That would make it behave more like as it were triggered by a DOM event. I'm sure JQuery has a specific method of triggering an event registered through it's DOM event functions. It would also be an option to use that as it would probably also emulate the Event Object passed to "myfunction".

To generalize the question, JavaScript events are handled by associating an event type (onclick, onkeyup, onfocuse, etc) with a function (or multiple functions). The function is, of course, parsed, but is not evaluated until the associated event occurs. Also, the "function," in this context, is often referred to as an event handler or event callback .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM