Javascript get “clicked” element addEventListener

后端 未结 2 1470
情歌与酒
情歌与酒 2020-11-29 11:07

I know I can grab the element of an individual ID.

Anyway I can attach a listener to the parent div and pass the ID of the individual span that was clicked?

2条回答
  •  盖世英雄少女心
    2020-11-29 11:36

    If the user clicked on a node that was a child of the element the user wanted to test e.target will be a different node. The sensible way to check this nowadays is to listen at the document level and iterate the path (or use some delegation library, of which there are many):

    Add one event listener to the document:

    const isOnId = (path,id) => path.some(element => element.id === id);
    
    document.addEventListener('click',function(e) {
      if(isOnId(e.path,'two')) {
        //you clicked on or in element with an id two
      } else {
        //you clicked on something else
      }
    });
    

提交回复
热议问题