2010-08-11 125 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