admin管理员组文章数量:1296240
I have 2 divs with a js click event. One div is located in the other one.
But I dont want the outer div's click event to be triggered if I click the inner one. How can I prevent that?
I have 2 divs with a js click event. One div is located in the other one.
But I dont want the outer div's click event to be triggered if I click the inner one. How can I prevent that?
Share Improve this question asked Apr 26, 2016 at 15:01 dunnohowishouldnamemyselfdunnohowishouldnamemyself 1592 silver badges12 bronze badges 1- 1 Possible duplicate of Prevent execution of parent event handler – Nirpendra Patel Commented Apr 26, 2016 at 15:07
3 Answers
Reset to default 5By default, event handling starts at the lowest level of the DOM where you have defined a handler to handle the target event. Assuming you have defined event listeners higher in the parent chain to handle the same event, you will need to stop the propagation of the event if you do not wish for the event to be handled beyond the layer you intend for it to be handled in:
e.stopPropagation();
See what happens when you remove that line in the example below:
document.querySelector('.inner').addEventListener('click', function(e) {
alert('inner div clicked!');
e.stopPropagation();
});
document.querySelector('.outer').addEventListener('click', function() {
alert('outer div clicked!');
});
.outer {
width: 200px;
height: 200px;
background: blue;
}
.inner {
width: 100px;
height: 100px;
background: green;
}
<div class='outer'>
Outer
<div class='inner'>
Inner
</div>
</div>
Use event.stopPropagation();
Like this
document.getElementById("#seconddiv").addEventListener("click", function($event){
$event.stopPropagation();
});
Use event.stopPropagation:
document.getElementById('inner').addEventListener('click', function (event){
event.stopPropagation();
console.log ('Inner div clicked!');
});
https://jsfiddle/4L87qLte/
本文标签: javascriptHow to prevent click event from outer div if inner div is clickedStack Overflow
版权声明:本文标题:javascript - How to prevent click event from outer div if inner div is clicked - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741610267a2388217.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论