jquery - 禁用父元素上的click函数

sam*_*kon 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>
Run Code Online (Sandbox Code Playgroud)

当我点击按钮时,tr click事件也被调用.有没有办法禁用父元素上的click事件?我找到的唯一解决方案是将类添加到父元素,并在其单击函数内检查它.例如:

 <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>
Run Code Online (Sandbox Code Playgroud)

Rei*_*gel 14

使用 .stopPropagation()

$('tr').click(function(){
   window.alert('tr');
});
$(':input').click(function(e){
   e.stopPropagation();
   window.alert('input');
});
Run Code Online (Sandbox Code Playgroud)

演示