jquery阻止事件冒泡及解决办法 live

来源:互联网 发布:江恩正方软件 编辑:程序博客网 时间:2024/06/08 17:46

动态添加标签的live事件

注:jquery版本1.8之后不在支持live事件

在实际项目中遇到的问题,动态添加的标签
live阻止冒泡失效,无论是用return false还是用e.stopPropagation()都不能阻止冒泡发生
以下是自己总结的例子

html
<div id="box">   <a href="javascript:;" class="delete">init html</a></div> <button id="add">add html</button>
jq
 $(function() {     // 用click事件    $(document).click( function(event) {        console.log('click');        event.stopPropagation();    });    // 用delegate事件    $(document).delegate('.delete','click', function(event) {        console.log('delegate');        event.stopPropagation();    });    // 用live事件    $('.delete').live('click', function(event) {        console.log('live');        event.stopPropagation();        //return false;    });    // 新添加的a标签    $('#add').click(function() {        var html = '<a href="javascript:;" class="delete">new html 1</a>';        $('#box').append(html);    });    $('#box').click(function() {        console.log('box emit');    });});

解决办法:
我们知道event.stopPropagation()对click阻止冒泡有效,那就可以在新动态添加的标签上绑定click事件。

大神们可畅所欲言,大家互相讨论;共同学习。
小Z(本人)自己总结的经验,有不足的地方请留言我修改。

原创粉丝点击