Javascript Event Listener on click not working as expected

前端 未结 5 418
感动是毒
感动是毒 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:39

    If you click li ,you are current 2 step childnodes from parentNode div#div1

    div#div1 > ul > li[current target] //back parentNode to 2 times
    
    <script>
        document.body.addEventListener('click', function(e){
         if(e.target.parentNode.parentNode.id == "div1"){alert("hi")}
        })
    </script>
    
    0 讨论(0)
  • 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 <li> elements within the Dom. You can follow the tree towards the root with parentElement to access the <li> containing <div> 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 <div> element.

    0 讨论(0)
  • 2021-01-20 16:49

    You should use e.target.parentNode.parentNode.id =='div1' See the demo:

    document.body.addEventListener('click', function(e) {
      if (e.target.parentNode.parentNode.id == "div1") {
        alert("hi")
      }
    })
    <div id="div1">
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <ul>

    0 讨论(0)
  • 2021-01-20 16:54

    There are two elements associated with an event:

    1. event.currentTarget, which is the element that is actually calling the listener (i.e. the on which the listener has been attached), and
    2. event.target, which is the element on which the event actually occurred

    These can be the same element, parent and child, or ancestor and descendant (which is the case here).

    So a click on an LI makes it the target, and since the body's click handler calls the listener, it's the currentTarget, the DIV is neither. If you put the listener on the DIV, it will then become the currentTarget.

    Originally, nodes other than elements could be event targets, but in recent implementations only elements are targets.

    Some links:

    1. W3C DOM 4 Interface eventTarget
    2. W3C DOM 4 Event

    Note that that target and eventTarget are specified as (host) objects, they aren't necessarily elements though that is how they are mostly implemented in current browsers.

    0 讨论(0)
  • 2021-01-20 16:56

    If you want all the LI's in your body to be clicked, you can check against the nodeName.

    Here is the fiddle: https://jsfiddle.net/swaprks/f3crax1q/

    Javascript:

    document.body.addEventListener('click', function(e){
         if(e.target.nodeName == "LI"){alert("hi")}
    })
    
    0 讨论(0)
提交回复
热议问题