本文介绍了如何判断对jQuery html()的更改何时完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在使用jQuery更改标签的HTML,新的HTML可能是一个很长的字符串.

I'm using jQuery to change the HTML of a tag, and the new HTML can be a very long string.

$("#divToChange").html(newHTML);

然后,我想选择在新HTML中创建的元素,但是如果我将代码直接放在上一行之后,则似乎会创建带有长字符串的竞争条件,其中不一定要对html()进行更改完成渲染.在这种情况下,尝试选择新元素并不总是可行.

I then want to select elements created in the new HTML, but if I put the code immediately following the above line it seems to create a race condition with a long string where the changes that html() is making may not necessarily be finished rendering. In that case, trying to select the new elements won't always work.

我想知道的是,在对html()的更改完成渲染后是否会触发事件或以其他方式通知您?我遇到了jQuery watch插件,该插件可以作为变通办法,但并不理想.有没有更好的办法 ?

What I want to know is, is there an event fired or some other way of being notified when changes to html() have finished rendering ? I came across the jQuery watch plugin, which works alright as workaround but it's not ideal. Is there a better way ?

推荐答案

正如已经提到的注释器,JavaScript是单线程的,因此您无法获得竞争条件.

As a commenter already mentioned, JavaScript is single threaded, so you can't get race conditions.

但是,可能使您绊倒的事实是,在线程完成之前,UI不会基于JavaScript进行自身更新.这意味着整个方法必须完成,包括调用html(...)之后的所有代码,然后浏览器才会呈现内容.

What may trip you up however, is the fact that the UI will not update itself based on JavaScript, until a thread is finished. This means that the entire method must finish, including all code after you call html(...), before the browser will render the content.

如果调用html(...)之后的代码依赖于在继续之前重新计算的页面布局,则可以执行以下操作:

If your code after calling html(...) relies on the layout of the page being recalculated before continuing, you can do something like this:

$("#divToChange").html(newHTML);
setTimeout(function() {
    // Insert code to be executed AFTER
    // the page renders the markup
    // added using html(...) here
}, 1);

在JavaScript中使用时间为1setTimeout(...)将推迟执行,直到调用函数中的当前JavaScript代码完成并且浏览器已更新UI.这可能可以解决您的问题,尽管很难告诉您,除非您可以提供所再现错误的可重现示例.

Using setTimeout(...) with a time of 1 in JavaScript defers execution until after the current JavaScript code in the calling function finishes and the browser has updated the UI. This may solve your problem, though it is difficult to tell unless you can provide a reproducible example of the error you're getting.

这篇关于如何判断对jQuery html()的更改何时完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:29