1. 程式人生 > >jquery阻止事件冒泡及解決辦法 live

jquery阻止事件冒泡及解決辦法 live

動態新增標籤的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(本人)自己總結的經驗,有不足的地方請留言我修改。