在$each函数中操作元素的文本



我试图为用户显示$each循环中对象的传递百分比。在控制台中,我看到了正确的值,但在前端,直到$each循环完成,项目的内容才会显示,然后它显示100%。

<div id="editForm-loader">
<p><i class="fas fa-spinner fa-pulse"></i> Daten werden geladen <i class="info"></i> <input type="text" value="" class="info"></p>
</div>

success: function(response) {
var aData   = JSON.parse(response).data;
var count   = 0;
var loading = 0;
var rows    = Object.keys(aData).length;
$.each(aData, function(key, value) {
count++;
loading = Math.round((count*100)/rows);
$('#editForm-loader i.info').text(loading + '%');      // nothing changes in the frontend 
$('#editForm-loader input.info').val(progress + '%');  // to test, but also does not change
console.log($('#editForm-loader i.info').text());      // show the correct value
// at this point I do a lot with the data
// so the each function with over 100 items takes about 5 seconds total.
});
$('#editForm-loader').hide();
}

提示应该在ajax成功回调中执行

看起来渲染在时间上被阻止了

〔已解决〕

success: function(response) {
var aData     = JSON.parse(response).data;
var count     = 0;
var loading   = 0;
var items     = Object.keys(aData).length;
var aFields   = [];
for (var key in aData) {
aFields.push({'key': key,   'val': aData[key]});    // It is an assoc array, so I am writing it again to be able to access it with count.
}
var iV  = setInterval(function() {
loading  = Math.round(((count+1)*100)/items);
$('#editForm-loader i.info').text(loading + '%');
var key   = aFields[count].key;
var value = aFields[count].val;
// at this point I do a lot with the data
// so the each function with over 100 items takes about 5 seconds total.
if (++count >= items) {
clearInterval(iV);
$('#editForm-loader').hide();
}
}, 0);
}

您可以使用setTimeout()并在循环的每次迭代中增加延迟。

简化示例:

const data = [10, 30, 50, 70, 90, 100]
$.each(data, function(i, value) {
setTimeout(function() {    
$('#editForm-loader i.info').text(value + '%');
}, i * 500)// 1/2 second increments
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="editForm-loader"><i class="info"></i></p>

相关内容

  • 没有找到相关文章

最新更新