2011-08-22 62 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