暂停 jQuery 就绪事件,直到多个 HTML DOM 更新完成
我正在使用 jQuery 进行 AJAX 提交并接收包含多个 DOM ID 和我需要更新的相应 HTML 片段的 JSON 回复。因此,我执行了多个 jQuery.html
调用,例如 $('#id1').html('...'); $('#id2').html('...');
.
对于每个包含 ready
处理程序(例如 $(function(){...});
)的片段,都会立即触发该事件。我更愿意在所有更新完成后调用它一次。
有什么办法可以做到这一点吗?
从我到目前为止所读到的内容来看, a jQuery.trigger() 可用于手动触发准备就绪
事件。但我需要保存和恢复当前处理程序或通过以某种方式覆盖 jQuery 内部来推迟事件传递。后者是我想避免的,也许有一些我还不知道的最佳实践?
I am using jQuery to make AJAX submits and receive JSON replies containing multiple DOM IDs and corresponding HTML fragments that I need to update. Thus, I do multiple jQuery.html
calls like $('#id1').html('...'); $('#id2').html('...');
.
For every fragment containing a ready
handler like $(function(){...});
, the event is immediately triggered. I'd prefer to call it once after all updates were made.
Is there any way to do that?
From what I've read so far, a jQuery.trigger() could be used to manually trigger the ready
event. But I'd need to save and restore the current handlers or postpone event delivery by overwriting the jQuery internals somehow. The latter is something that I'd like to avoid, maybe there's some best practice I don't know yet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下
holdReady
函数。请参阅:http://api.jquery.com/jQuery.holdReady/
Have a look at the
holdReady
function.See: http://api.jquery.com/jQuery.holdReady/
我首先将视图中的 js 移动到外部 js 文件中,在其中可以从 ajax 回调函数调用它们。
当您发现页内就绪事件很快就会让您感到失控并且变得很难维护。重新获得控制权,将您的 js 命名空间划分为逻辑部分,并失去现成的依赖。
如果您在结束 body 标记之前包含 js,则无需准备语句。我能给出的最好建议是开始在应用程序生命周期中明确说明 js 何时被调用,而不是依赖于过度滥用的就绪语句。
Rebecca Murphy 就此撰写了一些非常好的文章/演示。
I would start by moving the js you have in your views into external js files where they can be invoked from the ajax callback functions.
As you are finding out in-page ready events can soon leave you feeling out of control and become very hard to maintain. Regain control, namespace your js up into logical sections and lose the ready reliance.
There is no need for ready statements if you include your js before the closing body tag. The best advice I can give is to start being explicit in your apps lifecycle about what js gets called when, rather than relying on the well over abused ready statement.
Rebecca Murphy has written some very good articles/presentations about this.