1

有没有办法在 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 并对其进行计时的相同原理。

谢谢!

4

1 回答 1

12

那么......在你发表评论之后,这改变了一切。

你不能让它在任何 javascript 运行时自动显示,因为没有真正的钩子。.trigger()但是,您可以通过使用和使用您自己的自定义事件来利用 jquery 自.bind()定义事件。

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');
}

然后注册一个.bind()事件,就像.ajaxStart().ajaxStop()

$('#Working').bind('Custom.StartWork', function() {
  $(this).show();
});

$('#Working').bind('Custom.EndWork', function() {
  $(this).hide();
});

这是一个有效的 jsFiddle 示例


更新:

您的 jsFiddle 中,您已经完成了 double 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异步和非阻塞的。

于 2012-06-05T22:26:34.940 回答