javascript点击事件分离

标签 javascript jquery html css

我想把点击事件分开

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:

http://jsfiddle.net/c5fomgp1/

不幸的是,如果你运行 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/

相关文章:

javascript - If/Else Jquery 标题动画

Javascript 计时

jquery - 一起匹配表

javascript - .slideToggle on .click 功能不起作用

javascript - 在 Javascript 中递归调用函数?

javascript - 在 wordpress 上使用自定义 CSS 制作动画

php - jquery/php .css() 函数不起作用

c# - 用 HTML5 播放 wav

javascript - 如果 div 包含特定的文本字符串,则更改背景颜色

javascript - 在 HTML/CSS/JS 中制作修复缩放时间线