How can I stop the trigger of the outer div event when I click the inner element? And all the events are bound to $(document.body),so i think i should not stop event stopPropagation. When I click $(".logLi"), I just want to trigger the inner ele event. What is wrong with my code and how can i solve the problem? here is my code
<div class="clomn">
<div class="logLi">
<span>aaaaaaa</span><em>bbbbbb</em>
</div>
</div>
$(document.body).on("click", ".clomn .logLi", function(e) {
console.log("inner");
})
$(document.body).on("click", ".clomn", function(e) {
console.log("outer")
})
You can prevent the propagation of the event, but I prefer to check in the parent click handler to check whether it has occurred in a child element then discard it
$(document.body).on("click", ".colmn .logLi", function(e) { console.log("inner: 2"); }) $(document.body).on("click", ".colmn", function(e) { if ($(e.target).closest('.colmn .logLi').length == 0) { console.log("outer"); } }) $(".colmn .logLi").click(function() { console.log('inner: 1') })
.colmn { border: 1px solid red; padding: 15px; } .logLi { border: 1px solid green; padding: 15px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="colmn"> <div class="logLi"> <span>aaaaaaa</span><em>bbbbbb</em> </div> </div>
find by parent class name of e.target
,if you clicked inside .logLi
your parent class will be .logLi
. Do not need two click functions .
$(document.body).on("click", ".clomn .logLi", function(e) {
if($(e.target).parent().attr("class") == "logLi"){
console.log("inner");
}
else{
console.log("outer");
}
});
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.