我可以在此 if 语句中对返回的元素调用超时函数吗?
var data = 'some stuff';
if(data){
return jQuery('<div class="thisDiv"></div>').html(data);
}
我试过以下方法:
if(data){
setTimeout(function() {
return jQuery('<div class="thisDiv"></div>').html(data);
}, 100);
}
但我在控制台中收到此错误:
Uncaught TypeError: Cannot read property 'nodeType' of undefined
最佳答案
return
语句将从您传递给 setTimeout
函数的匿名函数返回,而不是包含 if
语句范围的函数.尝试将回调传递给包含 if
语句的函数,然后使用 data
作为参数调用该回调。
function delayedReturn(callback) {
if(data) {
setTimeout(function() {
callback(jQuery('<div class="thisDiv"></div>').html(data));
}, 100);
}
}
关于javascript - 我可以在此 if 语句中对返回的元素调用超时函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136178/