我需要在这个 for 循环中创建一个小的延迟:
for (i = 1; i <= cloneIndex; i++) {
var myElem = document.getElementById('form' + i);
if (myElem != null) {
function postData() {
return {
udd: document.getElementById('udd').value,
data: date_in,
hora_ini: hour_in,
hora_fim: hour_out,
cat: $('#form' + i).find('select[id="cat"]').val(),
m1: $('#form' + i).find('select[id="q1"]').val(),
m2: $('#form' + i).find('select[id="q2"]').val(),
m3: $('#form' + i).find('select[id="q3"]').val(),
m4: $('#form' + i).find('select[id="q4"]').val(),
m5: $('#form' + i).find('select[id="q5"]').val()
}
}
var newItem = postData();
$2sxc(@Dnn.Module.ModuleID).webApi.post('app/auto/content/audits', {}, newItem);
}
}
在stackoverflow示例之后,我尝试了这个解决方案:
for (i = 1; i <= cloneIndex; i++) {
(function(i){
setTimeout(function(){
var myElem = document.getElementById('form' + i);
if (myElem != null) {
function postData() {
return {
udd: document.getElementById('udd').value,
data: date_in,
hora_ini: hour_in,
hora_fim: hour_out,
cat: $('#form' + i).find('select[id="cat"]').val(),
m1: $('#form' + i).find('select[id="q1"]').val(),
m2: $('#form' + i).find('select[id="q2"]').val(),
m3: $('#form' + i).find('select[id="q3"]').val(),
m4: $('#form' + i).find('select[id="q4"]').val(),
m5: $('#form' + i).find('select[id="q5"]').val()
}
}
var newItem = postData();
$2sxc(Dnn.Module.ModuleID).webApi.post('app/auto/content/audits', {}, newItem);
}
}, 1000 * i);
}(i));
}
然而,这破坏了内部的功能。看来 myElem 现在总是为空。“我”太多?我怎样才能解决这个问题?
没关系。代码不起作用的原因很简单。下面的其余代码没有等待延迟循环结束,所以它实际上破坏了函数。
这修复了它(放置在 setTimeout 函数中):
k++;
if (k == cloneIndex) {rest of the code that needs the loop to end}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句