Reputation: 6814
Someone told me sometimes event delegate more efficient.
<ul id="test">
<li>aaaaa<li>
<li>bbbbb <p>xxxxx<p> </li>
<li>ccccc<li>
</ul>
//script
var li = document.getElementByTagName('li');
for(var i=0,len=li.length;i<len;i++){
li[i].addEventListener('click',function(){ alert(this.innerHTML); },false);
}
//event delegate
var ul = document.getElementById('test');
ul.addEventListener('click',function(e){
if(e.target == 'li'){
alert(e.target.innerHTML);
}
},false);
It works not good when you click 'p' in 'li'. I know jquery has method 'on',it's useful. I try to read jquery source code ,but can not understand how to implement a delegate function work under complexity DOM.
Upvotes: 0
Views: 222
Reputation: 340045
In this code:
//event delegate
var ul = document.getElementById('test');
ul.addEventListener('click',function(e){
if(e.target == 'li'){
alert(e.target.innerHTML);
}
},false);
the (single) event handler will be called for any click anywhere in the <ul>
element.
If you wish to find which <li>
received the click, even if the click was actually in some child element, you need to climb the DOM tree until you find the desired element.
//event delegate
var ul = document.getElementById('test');
ul.addEventListener('click',function(e) {
var el = e.target;
while (el) {
if (el.tagName === 'li') {
alert(el.innerHTML);
break;
} else {
el = el.parentNode; // climb the tree
if (el === this) break; // but not too far!
}
}
}, false);
The second parameter to jQuery's .on
does that DOM climbing for you - it emulates the DOM's event bubbling until it finds the element that matches the specified selector.
Upvotes: 3