Home  >  Article  >  Web Front-end  >  jquery prevents event bubbling and its solution

jquery prevents event bubbling and its solution

一个新手
一个新手Original
2017-09-13 10:05:582097browse


Live event for dynamically adding tags

Note: jquery no longer supports live events after version 1.8

In Problems encountered in actual projects, dynamically added tags
Live prevents bubbling from happening. Neither return false nor e.stopPropagation() can prevent bubbling from happening
The following is an example I summarized

html
<p id="box"> 
  <a href="javascript:;" class="delete">init html</a>
</p> 
<button id="add">add html</button>
jq
 $(function() {

     // 用click事件
    $(document).click( function(event) {
        console.log(&#39;click&#39;);
        event.stopPropagation();
    });

    // 用delegate事件
    $(document).delegate(&#39;.delete&#39;,&#39;click&#39;, function(event) {
        console.log(&#39;delegate&#39;);
        event.stopPropagation();
    });

    // 用live事件
    $(&#39;.delete&#39;).live(&#39;click&#39;, function(event) {
        console.log(&#39;live&#39;);
        event.stopPropagation();
        //return false;
    });

    // 新添加的a标签
    $(&#39;#add&#39;).click(function() {
        var html = &#39;<a href="javascript:;" class="delete">new html 1</a>&#39;;
        $(&#39;#box&#39;).append(html);
    });

    $(&#39;#box&#39;).click(function() {
        console.log(&#39;box emit&#39;);
    });

});

Solution:
We know that event.stopPropagation() is effective for click to prevent bubbling , then you can bind the click event to the newly dynamically added label.

The above is the detailed content of jquery prevents event bubbling and its solution. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn