重置后jQuery attr()没有在Bootstrap按钮上工作

我有一个非常简单的代码,不起作用,我不明白我错过了什么。

外部资源

   

HTML

 

JavaScript的

 $(document).ready(function () { $("#btn-id").button(); $("#btn-id").click(function () { //$("#btn-id").attr("disabled",true); $(this).button('loading'); setTimeout(function () { //this desn't work. The button resets but it doesn't get disabled afterwards $("#btn-id").button('reset').attr("disabled", true); //the bellow line works as expected //$("#btn-id").button('reset').addClass("btn-success"); }, 2000); }); }); 

似乎在button('reset') ,我可以添加类addClass('someclass')但我不能再禁用该按钮了。

为什么这不起作用,我该如何解决?

的jsfiddle

不确定这是否正确,但您可以使用解决方法

 $(document).ready(function () { $("#btn-id").button(); $("#btn-id").click(function () { $(this).button('loading'); setTimeout(function () { $("#btn-id").addClass('btn-success').data('loading-text', 'OK').button('loading') }, 2000); }); }); 

小提琴

您必须在disabled属性的基础上添加一个“禁用”类(它在bootstrap 3中的工作方式相同):

 $("#btn-id").addClass('btn-success').attr('disabled', 'disabled').addClass('disabled').html('OK'); 

的jsfiddle

问题是Button.prototype.setState()方法中使用的setTimeout:

https://github.com/twitter/bootstrap/blob/master/js/bootstrap-button.js#L46

这是一个解决方法:

 var $btn = $('.btn-save'); $btn.button('reset'); setTimetout(function() { $btn.attr('disabled', 'disabled'); // Disables the button correctly. }, 0); 

(小提琴: http : //jsfiddle.net/f0t0n/BKXVA/ )


资料来源: https : //github.com/twbs/bootstrap/issues/6242
归功于: https : //github.com/f0t0n

使用.prop()代替.attr()

更新的代码

 $(document).ready(function () { $("#btn-id").button(); $("#btn-id").click(function () { $("#btn-id").prop("disabled",true); $(this).button('loading'); setTimeout(function () { //this desn't work. The button resets but it doesn't get disabled afterwards $("#btn-id").button('reset').prop("disabled", true); //the bellow line works as expected //$("#btn-id").button('reset').addClass("btn-success"); }, 2000); }); }); 

jsFiddle演示

最好的解决方案是:

 $(document).ready(function () { $btn = $("#btn-id").button(); $btn.click(function () { $(this).data('loading-text', 'Loading wait...'); $(this).button('loading').delay(1000).queue(function() { $(this).button('reset'); $(this).dequeue(); }); }); // You can callback after completion, essential for those who need to add classes $('#reset-button').click(function () { $btn.button('reset'); $btn.dequeue().delay(100).queue(function(){ console.log('Loading completed'); // This button $(this).addClass('loading-completed'); // And very important for who callback function, examples: /* if (typeof callback === 'function') { callback(this); } */ });// enable button }); });//ready