如何显示jQuery中的加载微调器?
时间:2020-03-05 18:54:55 来源:igfitidea点击:
在原型中,我可以使用以下代码显示"正在加载..."图像:
var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); function showLoad () { ... }
在jQuery中,我可以使用以下命令将服务器页面加载到元素中:
$('#message').load('index.php?pg=ajaxFlashcard');
但是如何像在Prototype中一样将加载微调器添加到此命令?
解决方案
回答
有两种方法。我的首选方式是将一个函数添加到元素本身上的ajaxStart / Stop事件。
$('#loadingDiv') .hide() // Hide it initially .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }) ;
每当我们执行任何Ajax调用时,ajaxStart / Stop函数都会触发。
更新:从jQuery 1.8开始,文档指出.ajaxStart / Stop
仅应添加到document
上。这会将上面的代码片段转换为:
var $loading = $('#loadingDiv').hide(); $(document) .ajaxStart(function () { $loading.show(); }) .ajaxStop(function () { $loading.hide(); });
回答
$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse); showLoad(); function showResponse() { hideLoad(); ... }
http://docs.jquery.com/Ajax/load#urldatacallback
回答
我们可以在AJAX调用之前将动画图像插入DOM中,并执行内联函数将其删除...
$("#myDiv").html('<img src="images/spinner.gif" alt="Wait" />'); $('#message').load('index.php?pg=ajaxFlashcard', null, function() { $("#myDiv").html(''); });
这样可以确保动画在后续请求中从同一帧开始(如果重要)。请注意,旧版本的IE可能在动画方面存在困难。
祝你好运!
回答
的JavaScript
$.listen('click', '#captcha', function() { $('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />'); $.get("/captcha/new", null, function(data) { $('#captcha-block').html(data); }); return false; });
的CSS
#loading { background: url(/image/loading.gif) no-repeat center; }
回答
使用加载插件:http://plugins.jquery.com/project/loading
$.loading.onAjax({img:'loading.gif'});
回答
对于jQuery,我使用
jQuery.ajaxSetup({ beforeSend: function() { $('#loader').show(); }, complete: function(){ $('#loader').hide(); }, success: function() {} });