简体   繁体   中英

How to prevent child element executing onmousedown event

I've got the following markup on the page

<div id="box">
    <div id="box_child_one"></div>
    <div id="box_child_two"></div>
    <div id="box_child_three"></div>
</div>

I need to trigger the onmousedown event on all elements inside the #box div so i've got this javascript code:

var element = "#box";
document.querySelector(element).onmousedown = function() {
    alert("triggered");
};

However, I do not want onmousedown being triggered on the #box_child_three element. How can I achieve this?

Thank you.

Check event.target to find out which element was actually clicked on.

 var element = "#box"; document.querySelector(element).onmousedown = function(e) { if (e.target.id;== "box_child_three") { alert("triggered"); } };
 <div id="box"> <div id="box_child_one">one</div> <div id="box_child_two">two</div> <div id="box_child_three">three</div> </div>

You need to stopPropagation for the event when element three is clicked so that it doesn't bubble up to the parent ( box ) element.

 document.getElementById('box').addEventListener('click', () => alert('triggered') ); document.getElementById('box_child_three').addEventListener('click', e => e.stopPropagation() );
 <div id="box"> <div id="box_child_one">one</div> <div id="box_child_two">two</div> <div id="box_child_three">three</div> </div>

<div id="box">
    <div id="box_child_one" trigger></div>
    <div id="box_child_two" trigger></div>
    <div id="box_child_three"></div>
</div>

<script>
document.querySelector('#box').onclick = function(e){
  if(e.target.hasAttribute('trigger')){
    alert('event fired')
  }
}
</script>

I'd go for this. As you are now no longer relying on an id to carry this out making it more re-usable

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