我在一堆动态生成的 LI 元素上创建多个点击事件。但是当我点击其中任何一个时,只会发送最后一个 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();
});