简体   繁体   English

手动调用jQuery document.ready函数

[英]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() . 如果我发出一个AJAX请求并希望调用由$(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: 在您的AJAX请求完成后:

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. 使用此代码,所有.my-button点击都将由您的自定义函数处理,无论DOMReady上DOM中是否存在该按钮。

Note that: 注意:

  • $(document).ready(function() { ... }); can be minimized to $(function() { ... }); 可以最小化到$(function() { ... });
  • If you're using jQuery 1.7+, prefer .on over .delegate : $(document).on('click', .my-button', function() { }); 如果您使用的是jQuery 1.7+,则更喜欢.on over .delegate$(document).on('click', .my-button', function() { });
  • Prefer narrower context over broader, ie $('#close-parent').delegate over $(document).delegate 更喜欢更广泛的上下文,即$('#close-parent').delegate超过$(document).delegate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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