简体   繁体   中英

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.

MDN Documentation link on Event.stopPropagation()

JSFiddle Example

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);

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