Event Propagation Problem

I have a series of click events that cause me some distribution problems. The data for this container is loaded via ajax, therefore, the body on click method. Here is the code I have:

$(function () {
    $("body").on("click","#top-div",function(){
        console.log("top event");
    });

    $("body").on("click","#middle-div",function(e){
        e.stopPropagation();
    });

    $("body").on("click","#bottom-div",function(){
        console.log("bottom event");
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top-div">
  top
    <div id="middle-div">
      middle
        <div id="bottom-div">
          bottom
        </div>
    </div>
</div>
Run codeHide result

The top div has an event that the middle does not need to inherit, therefore stopPropagation(). However, the lower part should have its own event, but stopPropagation()from the middle it stops it from executing the event (if I delete the propagation of the stop, the lower event will fire, but by coincidence, as well as the top)

How can I get around this bubble issue?

+1
source share
3 answers

, , , div; div, , .

stopPropagation . #bottom-div, . , closest:

if (!$(e.target).closest('#bottom-div').length) {
    e.stopPropagation();
}

closest , id, closest , (a em, ) div s.

$(function () {
    $("body").on("click","#top-div",function(){
        console.log("top event");
    });

    $("body").on("click","#middle-div",function(e){
        if (!$(e.target).closest('#bottom-div').length) {
            e.stopPropagation();
        }
    });

    $("body").on("click","#bottom-div",function(){
        console.log("bottom event");
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top-div">
  top
    <div id="middle-div">
      middle
        <div id="bottom-div">
          bottom
        </div>
    </div>
</div>
Hide result
+2

div.

$(document).ready(function() {
  $("body").on("click", "div", function(event) {
    console.log(event.currentTarget.id + "event");
    if (event.target.id === "middle-div") {
      event.stopPropagation()
    }
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top-div">
  hello
  <div id="middle-div">
    hi
    <div id="bottom-div">
      bott-mid-v
    </div>
  </div>
</div>
Hide result

,

0

Bubbling , , - . , bottom-div:

bottom-divmiddle-divtop-div.

, , - , div, :

$("body").on("click","#top-div",function(e){

   if ( e.target.id ==='top-div'){
     //click in top div
   }

   if ( e.target.id ==='middle-div'){
     //click in middle div
   }

   if ( e.target.id ==='bottom-div'){
     //click in bottom div
   }



});

, div , , middle-div, div, bottom-div, , , , top-div, , .

http://maciejsikora.com/standard-events-vs-event-delegation/.

0

Source: https://habr.com/ru/post/1667380/


All Articles