简体   繁体   中英

Javascript : prevent click event being triggered on children elements

I don't understand why when I add a click event listener on an element, its children triggers it too.

I want that the parent is triggered even if the children are clicked, which should be the normal behavior I think.

Heres the code :

 var jobsList = document.querySelectorAll('.job_list .job'); for (var i = 0; i < jobsList.length; i++) { jobsList[i].addEventListener('click', _onChangeJob, false); } function _onChangeJob(e){ // When The children (.job_title, .job_date) is clicked, this function is called. I want only the parent to be clicked event if the children are clicked. } 
 <div class="job_list"> <div class="job active" data-job="1"> <p class="job_title">Job</p> <p class="job_date">21.11.16</p> </div> <div class="job active" data-job="1"> <p class="job_title">Job</p> <p class="job_date">21.11.16</p> </div> </div> 

You can use e.target to check what has been clicked, then for example check if the jobsList collection contains the target element. If it does then one of the .job elements is the target, otherwise the target is a child element.

// convert to a regular array to get indexOf method
var jobsList = [].slice.call(document.querySelectorAll('.job_list .job'));

for (var i = 0; i < jobsList.length; i++) {
  jobsList[i].addEventListener('click', _onChangeJob, false);
}

function _onChangeJob(e){
  if( jobsList.indexOf( e.target ) !== -1 ){
    console.log( 'clicked on .job')
  }
  else {
    console.log( 'clicked on a child element')
  }
}

https://jsfiddle.net/4r7hLua2/

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