我想把点击事件分开
body
标签内的所有点击都必须在“outside table”中被提醒,
postit-table
类中的点击事件除外。
这是我的代码:
html
<table class="postit-table">
<tbody>
<tr class="postit-header">
<td>header</td>
</tr>
<tr>
<td><textarea class="postit-content"></textarea></td>
</tr>
</tbody>
</table>
CSS
.postit-table{
width: 200px;
height: 200px;
background-color: yellow;
}
javascript(jquery):
$("body").bind('click',':not(".postit-table,.postit-table tbody, .postit-table tr, .postit-table tbody tr td")', function (e) {
alert("clicked outside table!");
});
$(".postit-table").click(function(){
alert("clicked inside table!");
});
jsfiddle:
不幸的是,如果你运行 fiddle 应用程序,它仍然会调用外部表的点击事件:(
有人可以帮忙吗?
最佳答案
在 postit-table
点击事件上使用 stopPropagation()
:
这样做不会将点击事件传播到 body
元素
示例 - http://jsfiddle.net/e5jph1Lt/
$("body").on('click', function() {
alert("clicked outside table!");
});
$(".postit-table").on('click', function(evt) {
evt.stopPropagation();
alert("clicked inside table!");
});
作为旁注,如果您使用最新的 jQuery 版本,请使用 on()
而不是 bind()
关于javascript点击事件分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25638780/