lel
lel

Reputation: 11

how to javascript make "event delegation"

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

i want to click "li",then alert sth.

but click "2222" or "33333",there is no alert。

how to make li “click delegation”

document.body.addEventListener("click", function(e) {
  if (e.target && e.target.nodeName.toUpperCase() == "LI") {
    alert('click');
  }
}, false);
<ul>
  <li>11111111</li>
  <li><span>2222222222</span></li>
  <li><span>3333333333</span></li>
  <li>444444444</li>
</ul>

Upvotes: 0

Views: 45

Answers (1)

artgb
artgb

Reputation: 3233

You can loop all the parent elements of current target using .parentNode.

  document.body.addEventListener("click", function(e) {

  if (e.target) {
    var a = e.target;
    while (a) {
       if( a.nodeName.toUpperCase() == "LI")
       {
           alert('click');
           break;
       }
       a = a.parentNode;
    }
  }
}, false);
<ul>
  <li>11111111</li>
  <li><span>2222222222</span></li>
  <li><span><b>3333333333</b></span></li>
  <li>444444444</li>
</ul>

You can do more easily using jQuery.

  $(document).ready(function () {

    $("li").click(
        function () {
            alert();
        }            
    );
});
<ul>
  <li>11111111</li>
  <li><span>2222222222</span></li>
  <li><span><b>3333333333</b></span></li>
  <li>444444444</li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

Upvotes: 1

Related Questions