简体   繁体   中英

Event Delegation: can someone explain me this JavaScript code?

I'm studying the event delegation on a book and I'm not sure I understood very well the concept. I know that it is used to "attach" an event to a parent element instead of attaching it to all the children. But I think I would not be able to use it on my own without a good explanation.

 function getTarget(e) { if(!e) { e = window.event; } return e.target || e.srcEvent; } function itemDone(e) { var item, elParent, elGrandparent; item = getTarget(e); elParent = item.parentNode; elGrandparent = item.parentNode.parentNode; elGrandparent.removeChild(elParent); if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } var el = document.getElementById("shoppingList"); if (el.addEventListener) { el.addEventListener("click", function(e) { itemDone(e); }, false); } else { el.attachEvent("onclick", function(e) { itemDone(e); }); } 
 <ul id="shoppingList"> <li class="complete"><a href="itemDone.php?id=1">fresh figs</a></li> <li class="complete"><a href="itemDone.php?id=2">pine nuts</a></li> <li class="complete"><a href="itemDone.php?id=3">honey</a></li> <li class="complete"><a href="itemDone.php?id=4">balsamic vine</a></li> </ul> 

If you attach an event to a parent element, and click a child element, if the child element has a click event attached to it that will fire, javaScript will also go down a chain of sorts and fire events attached to parent elements unless you prevent that from happening.

html

<div id="parent">
    <div>child 1</div>
    <div>child 2</div>
    <div>child 3</div>
</div>

javascript

document.getElementById('parent').addEventListener('click', function(e){

    console.log(e.target.innerHTML);

});

jsfiddle

In my example the innerHTML of the child element that is click is logged to the console.

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