2010-08-11 176 views
8

上禁用點擊功能我有結構這樣jQuery的 - 父元素

<table><tr><td></td><td><input type="button" name="button"></td></tr></table> 
<script> 
$('tr').click(function(){window.alert('tr');}) 
$(':input').click(function(){window.alert('input');}) 
</script> 

當我點擊按鈕,點擊TR事件也被稱爲。有沒有什麼辦法可以禁用父元素的點擊事件?我發現的唯一解決方案是將類添加到父元素,並在其單擊函數中檢查它。 例如:

<script> 
$('tr').click(function(){ if(!$(this).hasClass('disable')) { window.alert('tr'); } $(this).removeClass('disable'); }) 
$(':input').click(function(){window.alert('input'); $(this).closest('tr').addClass('disable');}) 
</script> 
+0

我有完全相同的問題,它的解決方案是令人驚訝的很難找到檢查的傳播狀態。非常感謝你提出這個問題,並感謝所有回答者的貢獻。 – MOnsDaR 2013-02-14 19:57:58

回答

14

使用.stopPropagation()

$('tr').click(function(){ 
    window.alert('tr'); 
}); 
$(':input').click(function(e){ 
    e.stopPropagation(); 
    window.alert('input'); 
}); 

demo

+0

看起來好像太容易了,但像魅力一樣。 – 2012-08-21 09:02:00

+0

+1,請參閱有關問題的評論 – MOnsDaR 2013-02-14 19:58:41

3

.stopPropagation()可以工作,但如果您不想停止整個事件,那麼只要目標匹配就可以觸發它。

See this thread