admin管理员组文章数量:1332865
I've similar to this:
<ul>
<li class="parent">
<div class="child"></div>
</li>
</ul>
And I've two on click triggers.
$(document).on("click", ".parent", function(){
console.dir("parent clicked");
});
$(document).on("click", ".child", function(){
console.dir("child clicked");
});
If I click child, parent is also clicked! How do i avoid this?
/
I've similar to this:
<ul>
<li class="parent">
<div class="child"></div>
</li>
</ul>
And I've two on click triggers.
$(document).on("click", ".parent", function(){
console.dir("parent clicked");
});
$(document).on("click", ".child", function(){
console.dir("child clicked");
});
If I click child, parent is also clicked! How do i avoid this?
http://jsfiddle/Vd2GA/
Share Improve this question asked Nov 15, 2013 at 16:56 user796443user7964436 Answers
Reset to default 5Use either return false
or e.stopPropagation()
in child click event handler:
$(document).on("click", ".child", function(e) {
console.dir("child clicked");
return false; // e.stopPropagation();
});
DEMO: http://jsfiddle/Vd2GA/1/
$(document).on("click", ".parent", function(e){
e.stopPropagation();
console.dir("parent clicked");
});
$(document).on("click", ".child", function(e){
e.stopPropagation();
console.dir("child clicked");
});
should do
Prevent the propagation of event from the child.
$(document).on("click", ".parent", function () {
console.dir("parent clicked");
});
$(document).on("click", ".child", function (e) {
console.dir("child clicked");
e.stopPropagation();
});
Demo: Fiddle
Note: this technique is possible here only because jQuery does some behind the scene magic when event delegation is used else since both the handlers are registered to document object this cannot be done
Use event.stopPropagation
fiddle Demo
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$(document).on("click", ".child", function (e) {
e.stopPropagation();
console.dir("child clicked");
});
Read What is event bubbling and capturing?
Updated the fiddle here: http://jsfiddle/Vd2GA/2/.
$(document).on("click", ".parent", function(){
console.dir("parent clicked");
});
$(document).on("click", ".child", function(e){
e.stopPropagation();
console.dir("child clicked");
});
or you can use this condition if you need to be specific
$(document).on("click", ".parent", function(e){
if (e.target==this)
console.dir("parent clicked");
});
http://jsfiddle/Vd2GA/4/
本文标签: javascriptJquery on click child element triggers on click parent elementStack Overflow
版权声明:本文标题:javascript - Jquery on click child element triggers on click parent element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742288629a2447385.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论