简体   繁体   中英

How to fire child div event without firing parent div event?

I am trying to fire child div event but it seems that instead of child div , it is the parent div's click event that is getting fired. I tried using stopPropagation in child event but it doesnt seem to work.

 $(document).ready(function() { var lot = '<div class="divlot">This is a lot!</div>' var lineitem = '<div class="divlineitem">This is a lineitem!</div>' $("#container").on("click", function() { $("#container").append(lot); }); $(".divlot").on("click", function(e) { e.stopPropagation(); alert($(this).attr("class")); $(this).append(lineitem); }); }); 
 #container { background-color: grey; } .divlot { background-color: red; padding-left: 20px; } .divlineitem { background-color: blue; padding-left: 20px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container">Container</div> 

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

As of now, your are using direct event handler binding for divlot which doesn't exist in the page thus neither event handler work nor e.stopPropagation()

Since you are adding event dynamically you need to use Event Delegation using .on() delegated-events approach.

Bind event using

$("#container").on("click", ".divlot", function(e) {
    e.stopPropagation();
    alert($(this).attr("class"));
    $(this).append(lineitem);
});

 $(document).ready(function() { var lot = '<div class="divlot">This is a lot!</div>' var lineitem = '<div class="divlineitem">This is a lineitem!</div>' $("#container").on("click", function() { $("#container").append(lot); }); $("#container").on("click", ".divlot", function(e) { e.stopPropagation(); alert($(this).attr("class")); $(this).append(lineitem); }); }); 
 #container { background-color: grey; } .divlot { background-color: red; padding-left: 20px; } .divlineitem { background-color: blue; padding-left: 20px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container">Container</div> 

You are creating the child divs dynamically. So you should use event delegation for properly binding the events.

  $("#container").on("click",".divlot", function(e) {
    e.stopPropagation();
    alert($(this).attr("class"));
    $(this).append(lineitem);
  });

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM