[英]How to add event listeners to elements that are inside one another
This image is to explain what my problems is:这张图片是为了解释我的问题是什么:
I have a Detail-box and I have added the "click" event listener to it.我有一个详细信息框,并且已向其中添加了“单击”事件侦听器。 I want to jump to another page when anyone clicks this link.当有人单击此链接时,我想跳转到另一个页面。 Also, I what to add "click" event-listener to the button inside this box (for doing some other action).另外,我要向此框中的按钮添加“单击”事件侦听器(用于执行其他操作)。
The problem is whenever I click on the button the event-listener corresponding to the the box runs and the event-listener corresponding to the button does not.问题是每当我单击按钮时,与框对应的事件侦听器就会运行,而与按钮对应的事件侦听器则不会。
How do I solve this problem?我该如何解决这个问题? Any help would be great.任何帮助都会很棒。
If I understood correctly, you are looking for event.stopPropagation()
event property.如果我理解正确,您正在寻找event.stopPropagation()
事件属性。
MDN Documentation link on Event.stopPropagation() Event.stopPropagation() 上的 MDN 文档链接
const detailsAlert = e => {
alert('details alert!');
}
const buttonAlert = e => {
e.stopPropagation();
alert('button alert!');
}
document.getElementById("details").addEventListener('click', detailsAlert, false)
document.getElementById('btn').addEventListener('click', buttonAlert, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.