我正在一堆动态生成的LI元素上创建多个click事件。但是当我点击其中任何一个时,只会调度最后一个li的事件。
这有点难以解释,但这里有一个小提琴会让事情变得更清楚:
...和代码:
// Parent Class
function Parent(id, children) {
this.id = id;
this.children = children;
this.init();
}
Parent.prototype = {
init: function () {
this.addEventHanlders()
},
addEventHanlders: function () {
addEventListener('childEvent', function (e) {
e.stopPropagation()
// console.log('childEvent', e.title)
});
},
render: function () {
var ul = document.createElement('ul');
ul.setAttribute('id', this.id)
for (var i = this.children.length - 1; i >= 0; i--) {
ul.appendChild(this.children[i].render());
};
document.body.appendChild(ul);
}
}
// Child Class
function Child(title) {
this.title = title;
this.li = null
this.event = document.createEvent("Event");
};
Child.prototype = {
render: function () {
_this = this;
this.li = document.createElement('li');
text = document.createTextNode(this.title);
a = document.createElement('a');
a.setAttribute('href', '#');
a.appendChild(text);
this.li.appendChild(a);
this.li.setAttribute('class', 'child');
this.li.addEventListener('click', this.clickEventHandler, true);
return this.li;
},
clickEventHandler: function (e) {
e.preventDefault();
_this.changeColor();
_this.fireEvent();
e.target.removeEventListener('click', this.clickEventHandler)
},
changeColor: function (color) {
color = color || 'red';
this.li.style.backgroundColor = color;
},
fireEvent: function () {
console.log('fireEvent', this.title);
this.event.initEvent("childEvent", true, true);
this.event.title = this.title;
document.dispatchEvent(this.event);
}
};
// Initialize
children = [new Child("Child 1"), new Child("Child 2"), new Child("Child 3"), new Child("Child 4"), new Child("Child 5")]
parent = new Parent("parent", children)
$(function () {
parent.render();
});
答案 0 :(得分:2)
问题在于您将this
保存到全局变量_this
中,可以从任何地方访问。因此,您已获得Child
中最后一个_this
实例的链接。
请参阅我的示例:http://jsfiddle.net/5uecp/4/