Javascript Event Listener on click not working as expected

前端 未结 5 417
感动是毒
感动是毒 2021-01-20 15:54

I\'m trying to create one event listener to handle all my \"clicks\" by putting it on the body and doing some event delegation. A simple example of what i\'m trying to do i

5条回答
  •  清酒与你
    2021-01-20 16:46

    Here's with jquery for reference:

      $("li").on('click', function(){
          var y = this.parentElement.parentElement.id;
          if (y === 'div1')
            alert(y);
      })
    

    This event is attached to all

  • elements within the Dom. You can follow the tree towards the root with parentElement to access the
  • containing
    element's id property.

    Alternatively:

    $("div").on('click', function(){
      var y = this.id;
      if (y === 'div1')
        alert(y);
    })
    

    However, this fires on every click within any

    element.

提交回复
热议问题