有没有一种编程方式可以知道 jQuery 的 DOM 更新何时完成?
例如:
var $myContainer = $('#myContainer');
$myContainer.html(someHtml);
var width = $myContainer.height();
var height = $myContainer.height();
如果 #myContainer 是一个空 div,宽度和高度仍为零。解决方案是使用超时:
var $myContainer = $('#myContainer');
$myContainer.html(someHtml);
setTimeout(function () {
var width = $myContainer.height();
var height = $myContainer.height();
}, 500);
但是,我不喜欢其中的幻数。如果它是一个非常慢的浏览器怎么办?是否有任何可靠的跨浏览器方法可以告诉我浏览器何时呈现更改?
For example:
var $myContainer = $('#myContainer');
$myContainer.html(someHtml);
var width = $myContainer.height();
var height = $myContainer.height();
If #myContainer was an empty div, width and height would still be zero. A solution is to use a timeout:
var $myContainer = $('#myContainer');
$myContainer.html(someHtml);
setTimeout(function () {
var width = $myContainer.height();
var height = $myContainer.height();
}, 500);
However, I don't like the magic number in there. What if its a really slow browser? Is there any reliable cross browser method available to tell me when the browser has rendered the changes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以可靠地使用
0
进行超时。它实际上不会是 0 毫秒,你知道,大多数浏览器至少会设置为 5 或 10 毫秒,但仅仅屈服于浏览器的行为就足够了。也就是说,我没有立即找到一个不能立即获得(新)高度的浏览器,没有产量(甚至是 IE6!)。但如果根据标记等,有一个……我不会感到惊讶。
You can use
0
for the timeout, reliably. It won't actually be 0ms, you understand, most browsers will make it at least 5 or 10, but just the act of yielding to the browser is sufficient.That said, I'm not immediately finding a browser that doesn't get the (new) height right immediately, without a yield (even IE6!). But I wouldn't be surprised if, depending on markup and such, there were one...
感觉像是黑客,但可能有效:将脚本元素添加到 DOM 作为最后一个元素。所有浏览器都应该在所有其他元素“解决”之后执行该操作。
Feels like a hack but might work: Add a script element to the DOM as the last element. All browsers should execute that after all the other elements have "settled."
你用的是ajax吗?
所以你可以使用 jQuery“加载”。
Are you using ajax?
So you can use jQuery 'load'.