(4)事件委托
事件是JavaScript非常重要的一部分。我们想给一个列表中的链接绑定点击事件,一般的做法是写一个循环,给每个链接对象绑定事件,HTML代码如下:
<h2>Great Web resourcesh2>
<ul id="resources">
<li><a href="http://opera.com/wsc">Opera Web Standards Curriculuma>li>
<li><a href="http://sitepoint.com">Sitepointa>li> <li><a href="http://alistapart.com">A List Aparta>li>
<li><a href="http://yuiblog.com">YUI Bloga>li> <li><a href="http://blameitonthevoices.com">Blame it on the voicesa>li>
<li><a href="http://oddlyspecific.com">Oddly specifica>li>
ul>
<ul id="resources">
<li><a href="http://opera.com/wsc">Opera Web Standards Curriculuma>li>
<li><a href="http://sitepoint.com">Sitepointa>li> <li><a href="http://alistapart.com">A List Aparta>li>
<li><a href="http://yuiblog.com">YUI Bloga>li> <li><a href="http://blameitonthevoices.com">Blame it on the voicesa>li>
<li><a href="http://oddlyspecific.com">Oddly specifica>li>
ul>
脚本如下:
// Classic event handling example
(function(){
var resources = document.getElementById('resources');
var links = resources.getElementsByTagName('a');
var all = links.length;
for(var i=0;i<all;i++){
// Attach a listener to each link links[i].addEventListener('click',handler,false);
};
function handler(e){ var x = e.target;
// Get the link that was clicked alert(x); e.preventDefault();
};
})();
(function(){
var resources = document.getElementById('resources');
var links = resources.getElementsByTagName('a');
var all = links.length;
for(var i=0;i<all;i++){
// Attach a listener to each link links[i].addEventListener('click',handler,false);
};
function handler(e){ var x = e.target;
// Get the link that was clicked alert(x); e.preventDefault();
};
})();
更合理的写法是只给列表的父对象绑定事件,这样可行的原理在于事件是支持冒泡的,代码如下:
(function(){
var resources = document.getElementById('resources');
resources.addEventListener('click',handler,false);
function handler(e){
var x = e.target;
// get the link tha if(x.nodeName.toLowerCase() === 'a'){
alert('Event delegation:' + x); e.preventDefault();
} };
})();
var resources = document.getElementById('resources');
resources.addEventListener('click',handler,false);
function handler(e){
var x = e.target;
// get the link tha if(x.nodeName.toLowerCase() === 'a'){
alert('Event delegation:' + x); e.preventDefault();
} };
})();