有没有办法在JavaScript函数运行时显示正在加载的图像。我有一个大约需要2-5秒,如果我能有类似jQuery-ajax函数的东西就好了
$("#loading").bind("ajaxStart", function(){
$(this).attr("style", "visibility: visible")
}).bind("ajaxStop", function(){
$(this).attr("style", "visibility: hidden")
});澄清编辑:
这个想法是,每当JavaScript函数运行并接管时,比如3/4秒,加载的图像就会显示出来。它实际上与这个ajax函数没有任何关系,只是始终捕获正在运行的JavaScript并对其计时的相同原则。
谢谢!
发布于 2012-06-06 06:26:35
好吧那..。在你评论之后,一切都变了。
你不能让它在任何javascript运行时自动显示,因为它没有真正的钩子。但是,您可以使用自己的自定义事件通过使用.trigger()和.bind()来利用jquery自定义事件。
function myFunctionThatDoesSomething() {
$('body').trigger('Custom.BeginWork');
// Do Something ...
$('body').trigger('Custom.EndWork');
}尽管长时间运行的操作可能应该异步完成,但不会阻塞事件:
$("#Something").click(function() {
$('body').trigger('Custom.BeginWork');
setTimeout(function() { DoWorkFunction(/* you can pass params here if you need */); }, 0);
// Causes it to be executed in the background 0ms from now
});
function DoWorkFunction() {
// Stuff...
$('body').trigger('Custom.EndWork');
}然后注册一个类似于.ajaxStart()和.ajaxStop()的.bind()事件
$('#Working').bind('Custom.StartWork', function() {
$(this).show();
});
$('#Working').bind('Custom.EndWork', function() {
$(this).hide();
});这是一个working jsFiddle Example。
更新:
在your jsFiddle中,您已经执行了两次setTimeout。这里:
setTimeout(function() {
// Call Operation Here
try { setTimeout(function () { LongRunningOperation(10000); }, 1000);
}
finally
{
$("body").trigger('Custom.End');
}
}, 50); // 50ms delay because some browsers *cough*IE*cough* are slow at rendering dom changes这意味着:

因此,Custom.End事件是在调度长时间运行的函数之后触发的,而不是在它完成时触发的。setTimeout是异步和非阻塞的。
https://stackoverflow.com/questions/10905829
复制相似问题