Javascript 检查jQuery中动态生成的元素? 请考虑以下代码: function autoRecursiveLoad(checkingElementId) { if (checkingElementId.length) { return; } else { var targetId = $("#targetContent"); var requestUrl = $('#ajaxUrl').val(); $.ajax({ url: requestUrl, cache: false, type: "POST", async:false, beforeSend: function(){ }, complete: function(){ autoRecursiveLoad(checkingElementId); }, success: function(data) { targetId.append(data); }, error: function(e) { } }); } }
在代码中:Javascript 检查jQuery中动态生成的元素? 请考虑以下代码: function autoRecursiveLoad(checkingElementId) { if (checkingElementId.length) { return; } else { var targetId = $("#targetContent"); var requestUrl = $('#ajaxUrl').val(); $.ajax({ url: requestUrl, cache: false, type: "POST", async:false, beforeSend: function(){ }, complete: function(){ autoRecursiveLoad(checkingElementId); }, success: function(data) { targetId.append(data); }, error: function(e) { } }); } },javascript,jquery,Javascript,Jquery,在代码中:checkingElementId是动态生成的元素的id。我使用checkingElementId.length查看它是否已经存在,如果不存在,则发送ajax请求以加载内容,创建id为checkingElementId的div,然后附加到targetId,然后执行递归调用 问题是id为checkingElementId的div已成功生成,但用于检查其是否存在的代码(checkingElementId.length)从未工作。因此,上述函数将永远循环。我做错了什么吗?我不知道这是否是最好
checkingElementId
是动态生成的元素的id。我使用checkingElementId.length
查看它是否已经存在,如果不存在,则发送ajax请求以加载内容,创建id为checkingElementId
的div,然后附加到targetId
,然后执行递归调用
问题是id为
checkingElementId
的div已成功生成,但用于检查其是否存在的代码(checkingElementId.length
)从未工作。因此,上述函数将永远循环。我做错了什么吗?我不知道这是否是最好的解决方案,但这对我来说很有效,我会动态触发DomainNodeInserted事件,因此函数更新如下:
function autoRecursiveLoad(checkingElementId) {
$(document).on('DOMNodeInserted', checkingElementId, function () {
// do something when the new dynamically generated item (checkingElementId) added to the page
});
if (checkingElementId.length) {
return;
}
else {
var targetId = $("#targetContent");
var requestUrl = $('#ajaxUrl').val();
$.ajax({
url: requestUrl,
cache: false,
type: "POST",
async:false,
beforeSend: function(){
},
complete: function(){
autoRecursiveLoad(checkingElementId);
},
success: function(data) {
targetId.append(data);
},
error: function(e) {
}
});
}
}
这里的checkingElementId是什么?如果不查看html代码就无法更正它,因为您永远不会更改
checkingElementId
的值,因此无论它是什么,都无法停止循环。使用async:false
是非常糟糕的做法,因为它会阻止问题中已经提到的UII:checkingElementId是附加到的动态生成的div的id使用requestUrl发送ajax请求时使用targetId。我不需要更新这个checkingElementId,因为它是动态生成并附加到页面的。当然,大多数时候ajax调用都处于异步模式,但在某些情况下,ajax必须处于同步状态(async:false)才能满足特定的需求。