有没有办法在JavaScript函数运行时显示加载图像.我有一个需要大约2-5秒,如果我可以有类似jQuery-ajax功能的东西会很好
$("#loading").bind("ajaxStart", function(){
$(this).attr("style", "visibility: visible")
}).bind("ajaxStop", function(){
$(this).attr("style", "visibility: hidden")
});
Run Code Online (Sandbox Code Playgroud)
澄清编辑:
这个想法是每次JavaScript函数运行并接管时,比如3/4秒,就会显示加载图像.它实际上与这个ajax函数无关,就像始终捕获正在运行的JavaScript并对其进行计时一样.
谢谢!
那么......在您评论之后,这会改变一切.
当任何javascript运行时,你不能自动显示它,因为没有真正的钩子.但是,您可以通过使用.trigger()和.bind()使用自己的自定义事件来利用jquery自定义事件.
function myFunctionThatDoesSomething() {
$('body').trigger('Custom.BeginWork');
// Do Something ...
$('body').trigger('Custom.EndWork');
}
Run Code Online (Sandbox Code Playgroud)
虽然长时间运行的操作可能应该是异步完成的,所以它们不会阻塞事件:
$("#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');
}
Run Code Online (Sandbox Code Playgroud)
然后注册一个.bind()类似.ajaxStart()和的事件.ajaxStop()
$('#Working').bind('Custom.StartWork', function() {
$(this).show();
});
$('#Working').bind('Custom.EndWork', function() {
$(this).hide();
});
Run Code Online (Sandbox Code Playgroud)
这是一个有效的jsFiddle示例.
更新:
在你的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
Run Code Online (Sandbox Code Playgroud)
这转化为:

因此,Custom.End在调度要运行的长时间运行函数之后,事件将被触发,而不是在它完成时.setTimeout是异步和非阻塞的.
| 归档时间: |
|
| 查看次数: |
6101 次 |
| 最近记录: |