2011-08-22 69 views
1

我想知道是否有人可以帮我解决这个问题。Javascript禁用按钮

我有一个按钮定义为:

<input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/> 

我可以使用jQuery,标准JavaScript或道场禁用与onClick事件的按钮:

$('#myButton').attr('disabled', 'disabled'); 

我面临的问题是,即使尽管此代码禁用了按钮,但如果点击按钮,onClick事件仍会触发功能callMe()

如何使禁用按钮不能调用onClick函数?

+2

入住呼我的按钮是否被禁用? – Gelatin

+0

在附注上,你也可以像'attr('disabled',true)'那样传递'true',这样做可能会更清楚一些。 – pimvdb

+0

@Simon,不错的主意,但即使应用程序的某些部分不需要此功能,也需要在该功能中添加此检查 – t0mcat

回答

4

使用jQuery可以绑定来检查,如果你的按钮被禁用的功能:

$('#myButton').click(function() { 
    if (!$(this).is(':disabled')) { 
    callMe(); 
    } 
}); 
0
$('#myButton').click(function(){ 
    if(!$(this).is('[disabled=disabled]')){ 
     ... 
    } 
}); 
0

在禁用它相同的代码,只需删除onclick事件处理程序。

+0

嗨乔纳森,如何删除onClick事件处理程序? – t0mcat

1

由于您使用jQuery,使用

$('#myButton').click(function() { callMe(); this.unbind(); }); 

代替的onClick。

+0

嗨mblase,其实我现在正在使用这个标准的JavaScript。 – t0mcat

0

你应该使用jQuery附上点击处理,而不是将它们添加直列*

只需添加一个检查你的点击功能

$('#myButton').click(function(){ 
    var $this; 
    $this = $(this); 
    if ($this.is(':disabled')) return; 
    callMe(); 
}); 

另外,

$('#myButton').click(callMe); 

callMe() 
{ 
    var $this; 
    $this = $(this); 
    if ($this.is(':disabled')) return; 
    ...the rest of your code... 
} 

或者,如果你坚持使用它内联:

onclick="if ($(this).is(':disabled')) return; callMe();" 

*我regularlyrantabouthowHTML, CSS & JS适合MVC

的定义
+0

嗨zzzzzBov,我不坚持使用内联。我宁愿更好的解决方案,如果你说内联不好,我不会使用它:) – t0mcat

+0

@ t0mcat,我已经更新了我的答案,并指出了你应该避免内联JS的原因。 – zzzzBov

0

,而不是使用onclick属性,绑定到该事件

$('#myButton').click(function(e){ 
    // try it without this 
    if($(this).attr('disabled')) 
     return false; 
    callMe(); 
    e.preventDefault(); 
}); 

尝试没有检查,不知道它的必要。

0

这是一种做法。

$('#myButton').click(function(){ 
    if(!$(this).hasClass("disabled")){ 
    //Do stuff here 
    } 
}); 

要禁用按钮只需将禁用的类添加到它。

$('#myButton').addClass("disabled"); 

添加相应的风格指数中禁用类,使按钮看起来像禁用或者您也可以设定设置类沿disabled属性。

0

而不是......

$('#myButton').attr('disabled', 'disabled'); 

...使用... ...

$('#myButton') 
    .prop('disabled', 'disabled') // Sets 'disabled' property 
    .prop('onclick', null)   // Removes 'onclick' property if found 
    .off('click');     // Removes other events if found