JQuery脚本加载时间

6
如果我有一个按钮,可以触发jQuery脚本,那么有没有办法确保在脚本完成之前该按钮处于非活动状态?
3个回答

37

这是我喜欢扩展jQuery的一个领域:

$.fn.disable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined") this.disabled = true;
    });
}

$.fn.enable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined") this.disabled = false;
    });
}

然后你可以做:

$("#button").disable();
$("#button").enable();

我经常需要禁用/启用控件。


我更喜欢这个方案。你也可以轻松地改进该函数以更改文本。 - Raithlin

10

在脚本的开头某处(可能是按钮的点击事件),将按钮的 disabled 属性设置为 true:

$("#mybutton").attr("disabled", true);

完成后,删除该属性:

$("#mybutton").removeAttr("disabled");

编辑:

如果你想在执行操作时让界面略微变得更加美观,可以尝试在工作进行中更改按钮的文本。如果这是一个图像按钮,你可以将该按钮的src属性更改为友好的“请稍候”消息。以下是一个更改按钮文本的示例:

$("#mybutton").click(function() {
  var origVal = $(this).attr("value");

  $(this).attr("value", "Please wait...");
  $(this).attr("disabled", true);

  //Do your processing.

  $(this).removeAttr("disabled");
  $(this).attr("value", origVal);
});

3

感谢cletus提供的函数。我已经使用了你的函数并创建了我的函数来切换禁用元素。

$.fn.toggleDisable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined"){
                if(this.disabled){
                    this.disabled = false;
                }else{
                    this.disabled = true;
                }
        }
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接