我正在使用Twitter Bootstrap的按钮加载状态(http://twitter.github.com/bootstrap/javascript.html#buttons)。
HTML:
<input type="submit" class="btn" value="Register" id="accountRegister" data-loading-text="Loading..."/>
JS:
(function ($, undefined) {
$("#accountRegister").click(function () {
$(this).button('loading');
$.ajax({
type:"POST",
url:"/?/register/",
data:$("#loginForm").serialize(),
error:function (xhr, ajaxOptions, thrownError) {
$("#accountRegister").button('reset');
},
success:function (data) {
$("#accountRegister").button('reset');
}
});
return false;
})
})(jQuery);
但如果我有很多按钮,我需要写很多功能(?)。 当然我可以做这样的事情:
$(".ajax-button").bind("click", function() {
$(this).button("loading");})
我可以使用jQuery Ajax事件ajaxComplete
$(".ajax-button").bind("ajaxComplete", function() {
$(this).button("reset");})
但是当任何 Ajax请求完成时,所有按钮将被设置为正常状态。
如果用户单击 button1 然后单击 button2 (两个按钮都发送Ajax请求),当第一个Ajax请求完成时,它们将被设置为正常状态。如何确定我需要将哪个按钮设置为正常状态?
提前谢谢。
我只需要确定哪个按钮触发了某个操作(Ajax请求),将其设置为 loading ,并且当Ajax请求完成时将其设置为正常状态。
答案 0 :(得分:9)
我为我的问题找到了解决方案=) 在阅读jQuery文档后,我为我的系统编写了这段代码:
<强> core.js:强>
(function ($, undefined) {
$.ajaxSetup({
beforeSend:function (xhr, settings) {
if (settings.context != undefined && settings.context.hasClass('btn')) {
settings.context.button('loading');
}
},
complete:function () {
this.button('reset');
}
});
})(jQuery);
<强> account.js:强>
(function ($, undefined) {
$("#accountRegister").click(function () {
$.ajax({
context:$(this), // You need to set context to 'this' element
//some code here
});
return false;
})
})(jQuery);
这完美无缺。 希望这对某人有用。