首页 > 语言 > JavaScript > 正文

jQuery阻止事件冒泡具体实现

2024-05-06 14:35:06
字体:
来源:转载
供稿:网友

下面是html代码部分:

代码如下:
<body>
<div id="content">
    外层div元素
    <span>内层span元素</span>
    外层div元素
</div>

<div id="msg"></div>
</body>

对应的jQuery代码如下:

代码如下:
<script type="text/javascript">
$(function(){
    // 为span元素绑定click事件
    $('span').bind("click",function(){
        var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";//获取html信息
        $('#msg').html(txt);// 设置html信息
    });
    // 为div元素绑定click事件
    $('#content').bind("click",function(){
        var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>";
        $('#msg').html(txt);
    });
    // 为body元素绑定click事件
    $("body").bind("click",function(){
        var txt = $('#msg').html() + "<p>body元素被点击.<p/>";
        $('#msg').html(txt);
    });
})
</script>

当点击span时,会触发div与body 的点击事件。点击div时会触发body的点击事件。

如何防止这种冒泡事件发生呢?

修改如下:

代码如下:
<script type="text/javascript">
$(function(){
       // 为span元素绑定click事件
    $('span').bind("click",function(event){
        var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";
        $('#msg').html(txt);
        event.stopPropagation();    //  阻止事件冒泡
    });
    // 为div元素绑定click事件
    $('#content').bind("click",function(event){
        var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>";
        $('#msg').html(txt);
        event.stopPropagation();    //  阻止事件冒泡
    });
    // 为body元素绑定click事件
    $("body").bind("click",function(){
        var txt = $('#msg').html() + "<p>body元素被点击.<p/>";
        $('#msg').html(txt);
    });
})
</script>

event.stopPropagation(); // 阻止事件冒泡

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选