给很多元素添加事件的时候,将事件委托给所有元素的父节点来触发处理函数。
// 找到父节点,并添加click事件
document.getElementById('parent').addListener('click', function(e) {
// 检查事件目标e.target是否为li
if(e.target && e.target.nodeName.toUpperCase == 'LI') {
console.log('yep, i am li');
}
});e.type // 事件类型
e.target // 事件目标
e.target.nodeName // 事件目标节点的名称
e.stopPropagation(); // 阻止冒泡
e.preventDefault(); // 阻止默认行为
IE
event = e || window.e;
event.srcElement; // 事件目标
event.cancelBubble = false; // 阻止冒泡
event.cancelBubble = true; // 不阻止冒泡
event.returnValue = true; // 不阻止默认行为
event.returnValue = false; // 阻止默认行为使用代理
var delegate = function(client, clientMethod) {
return function() {
return clientMethod.apply(client, arguments);
};
};
var ClassA = function() {
var _color = 'red';
return {
getColor : function() {
console.log('Color:' + _color);
},
setColor : function(color) {
_color = color;
console.log(_color)
}
};
};
var a = new ClassA();
var d = delegate(a, a.setColor);
d('blue');