如果我有一个按钮,可以触发jQuery脚本,那么有没有办法确保在脚本完成之前该按钮处于非活动状态?
这是我喜欢扩展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();
我经常需要禁用/启用控件。
在脚本的开头某处(可能是按钮的点击事件),将按钮的 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);
});
感谢cletus提供的函数。我已经使用了你的函数并创建了我的函数来切换禁用元素。
$.fn.toggleDisable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined"){
if(this.disabled){
this.disabled = false;
}else{
this.disabled = true;
}
}
});
}