我有一个在客户端运行 2-3 秒的函数(没有 ajax 调用)。 我试图在此操作运行时显示“忙碌/处理”动画。
简化代码如下:
var ajaxContainer = $('.spinner');
// show
$(ajaxContainer ).show();
// long operation
var items = GetItems();
$.each(items, function (index, value) {
ProcessItem(value.itemID);
});
// hide
$(ajaxContainer ).hide();
但这并没有按预期工作。我得到的结果是操作运行时不显示微调器。尽管它确实显示操作何时结束。
我在网上看到一些帖子提到这可以通过使用windows.setTimeout()来完成。但由于此操作基于动态数量的项目,我不想提前设置特定的超时数。相反,我想在操作开始时显示微调器,并在操作完成时隐藏它。
有没有一种优雅的方式来实现这一点?
最佳答案
我认为您必须向 ProcessItem
函数添加一个回调参数,以便检查是否所有项目都已处理。试试这个方法:
function ProcessItem(id, callback){
//do process and after call callback function
callback();
}
var processedItemsQuantity = 0;
var ajaxContainer = $('.spinner');
ajaxContainer.show();
// long operation
var items = GetItems();
$.each(items, function (index, value) {
ProcessItem(value.itemID, function(){
if (items.length - 1 == processedItemsQuantity){
ajaxContainer.hide();
}
else processedItemsQuantity++;
});
});
关于javascript - 如何显示长时间非 ajax 操作的繁忙指示器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070573/