我将iframe中的body元素的html设置为字符串str,然后我想在下一行访问该内容(这里只是使用警告调用来显示内容)但是html和append函数没有在调用alert语句时完成.
$(function(){
....
$("#notes-tab span.add_draft").bind("click", function(e){
var str = '';
$(this).parent().siblings(".tab-content").children(".para").each(function(ind) {
str += $(this).find('div:first').html();
});
var curr = $("#content_rte").contents().find("body").html();
if (curr == ' ' || curr == '<br>') {
$("#content_rte").contents().find("body").html(str);
}
else {
$("#content_rte").contents().find("body").append(str);
}
alert($("#content_rte").contents().find("body").html());
});
});
Run Code Online (Sandbox Code Playgroud)
当然,html和append函数都不会进行回调.
有人能告诉我一个人在继续之前如何正常完成等待DOM的更改?
Gra*_*era 11
如果您使用的是jQuery,您可以依赖于.closest()确定您刚刚创建的元素是否具有父body标记,如果它确实存在,则意味着它已添加到DOM中.您可以编写如下所示的函数,以便在元素准备就绪时实际执行某些操作:
callWhenReady: function (selector, callback, scope) {
var self = this;
if ($(selector).closest('body').length) {
callback.call(scope);
} else {
setTimeout(function () {
self.callWhenReady(selector, callback, scope);
}, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
Cor*_*lou -7
除了在尝试检索 HTML 之前设置任意超时之外,实际上没有直接的等待方法。这样做的代码是:
// wait for 250 ms, then try and retrieve contents
setTimeout(function() {
alert($("#content_rte").contents().find("body").html());
}, 250);
Run Code Online (Sandbox Code Playgroud)
您应该尝试将超时设置得足够小,以免被注意到,但又足够大,以便允许内容更新,这样您就可以避免 250 毫秒以内的时间。
| 归档时间: |
|
| 查看次数: |
11476 次 |
| 最近记录: |