Javascript 等待将数据添加到Div
好的,我有一个div:Javascript 等待将数据添加到Div,javascript,html,Javascript,Html,好的,我有一个div: <div class="moreStuff"> <p>stuff in here matters</p></div> 这个“weirdFunction()”接受一些值,执行一些不重要的操作,并将其添加/追加到div.moreStuff 在“WeirdFunction()”之后,我有自己的函数: stuffIWantToDo(...); “stuffIWantToDo()”检查div.moreStuff并根据其中的数据做出
<div class="moreStuff"> <p>stuff in here matters</p></div>
这个“weirdFunction()”接受一些值,执行一些不重要的操作,并将其添加/追加到div.moreStuff
在“WeirdFunction()”之后,我有自己的函数:
stuffIWantToDo(...);
“stuffIWantToDo()”检查div.moreStuff并根据其中的数据做出反应
问题是“weirdFunction()”完成其业务并将其数据添加到div.moreStuff大约需要300毫秒,但我的函数“stuffIWantToDo()”在300毫秒之前就存在了;这意味着当运行“stuffIWantToDo()”时,div.moreStuff中没有任何内容
我想阻止“stuffIWantToDo()”运行,直到“weirdFunction()”将数据追加到div.moreStuff。尝试将stuffIWantToDo()作为weiredFunction()中的回调函数
检查这篇文章:如果您正在使用一些jQuery调用,那么我们需要查看它,正如@tymeJV已经说过的,看起来您在
weiredFunction函数中包含了一些async
代码
否则,您的代码必须同步工作,并且您唯一需要的就是调用stuffIWantToDo函数作为回调,或者在第一个函数的末尾调用
如果这些对您来说都没有意义,那么请使用古老而广为人知的setTimeout javascript函数
像
如果我理解正确,您就不可能更改Weired函数。基于这个假设,您必须编写一个小的基于时间间隔的观察程序,一旦内容发生更改,它就会启动您的函数
var stuffContent = '';
window.setInterval(function() {
var currentStuffContent = $('.moreStuff').html();
if(currentStuffContent == stuffContent) return;
stuffContent = currentStuffContent;
stuffIWantToDo();
}, 50);
但是,如果您可以简单地在weiredFunction中启动stuffIWantToDo作为回调,那将是最好的。听起来您的weiredFunction
执行异步操作,您应该发布它
function weiredFunction(callback) {
// finish the weird thing
// Call the callback
callback('some','stuff','there');
}
function stuffIWantToDo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
weiredFunction(foo);
function weiredFunction(takes,some,values){
/* some weired stuff here */
setTimeout(function() {
stuffIWantToDo(...);
}, 300);
}
var stuffContent = '';
window.setInterval(function() {
var currentStuffContent = $('.moreStuff').html();
if(currentStuffContent == stuffContent) return;
stuffContent = currentStuffContent;
stuffIWantToDo();
}, 50);