jQuery-禁用父元素上的单击功能 [英] jquery - disabling click function on parent element

查看:135
本文介绍了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 click事件.有什么办法可以禁用父元素上的点击事件?我发现的唯一解决方案是将类添加到父元素,并在其click函数中对其进行检查. 例如:

when i click on the button, tr click event also called. is there any way to disable click event on parent element? the only solution i found is to add class to parent element and inside its click function check for it. for example:

 <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>

推荐答案

使用 .stopPropagation()

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

这篇关于jQuery-禁用父元素上的单击功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆