简体   繁体   中英

Calling jQuery document.ready functions by hand

If I make an AJAX request and want to call all functions that were set up by $(document).ready() . How can I do it? Thank you

$(document).ready();

If that doesn't work, try this:

function startup() {

    // All your functions in here.

}

$(document).ready(startup);

And after your AJAX request is finished:

startup();

The easiest way is to use a shared function:

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

$.post('/', {}, function() {
    setup();
}, 'json');

But if you're using it to re-assign listeners, you would probably be able to get away with assigning them before they're created, like this:

$(document).ready(function() {
    $(document).delegate('.my-button', 'click', function() { });
});

Using this code, all .my-button clicks will be handled by your custom function, regardless of whether the button existed in your DOM upon DOMReady.

Note that:

  • $(document).ready(function() { ... }); can be minimized to $(function() { ... });
  • If you're using jQuery 1.7+, prefer .on over .delegate : $(document).on('click', .my-button', function() { });
  • Prefer narrower context over broader, ie $('#close-parent').delegate over $(document).delegate

而不是手动触发document.ready(这将是不好的做法恕我直言),创建一个名为setup的函数,它设置所有的侦听器等,并在需要重新应用等时调用此函数。

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