简体   繁体   中英

How can I fire jQuery outside document.ready block?

The common method of starting jQuery is putting it in

$(document).ready(function() {
    // put all jQuery stuff here
});

But what if I have a complicated site which uses basic jQuery in <head> and some custom functions that depend on the page type (eg if I have login page, fire some login ajax stuff).

So, how can I attach code to $(document).ready() or fire it later? Which JS syntax should I use?

Thanks for help!


My page structire is similar to this:

  1. Display static header using PHP's include()
  2. Add content inside <body></body>
  3. Display the template footer

<?php

include_once('system/classes/class.display.php');

$d = new IFDisplay();

$d->display_header(array('subtitle' => 'Log In')); <-- Here it displays static
                                                       head tags. There is
                                                       document.ready in there.
                                                       I can't change it.

?>

<script type="text/javascript">
AND WHAT DO I NEED TO PUT HERE
</script>

<div>...</div>

<?php

$d->display_footer();

?>

If you aren't worried about race conditions, you should be able to use this:

$(function(){
    //put your code here
});

As many times as you like.

If you have a block of code that you want to be able to run BOTH in a $(document).ready() function and sometime later like when an ajax call completes, then you can just define a function and call it both places like this:

// define this in the global scope or some other publicly available scope (not inside a document.ready() call).
function myOperation() {
   // put your code here
}

$(document.ready(function() {
    myOperation();
});

And, then sometime later (like in an ajax call in your other code), you can call that same function with this:

myOperation()

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