当我使用createElement创建元素时,appendChild不能使用eventListener访问它们。
在这种情况下
<div class="row">
<ul class="maldito mt-5">
</ul>
</div>
添加li元素后,无法使用eventListener定位它
var $ul = document.querySelector('.maldito');
var $li = $ul.querySelectorAll('li');
(function(){
var x = 0;
while ( x < 2) {
x++;
var addLi = document.createElement('li');
$ul.appendChild(addLi);
}
$li = $ul.querySelectorAll('li');
for ( var i = 0; i < $li.length; i++ ){
$li[i].textContent = "Some text";
}
window.addEventListener('DOMContentLoaded', function(){
for ( var i = 0; i < addLi.length; i ){
addLi[i].addEventListener('click', function(){
this.classList.add('active');
})
}
})
})()
答案 0 :(得分:0)
您应该保留对元素的引用,或者通过Event#currentTarget
访问事件处理程序附加到的元素。
const app = document.getElementById("app");
const words = [
"hello",
"world",
"foo",
"bar"
];
// Map words to array of HTMLElements
const wordElements = words.map(w => {
const el = document.createElement("div");
el.innerHTML = w;
return el;
});
// Append elements after we have created them
// Even though "el" reference is gone
wordElements.forEach(we => app.appendChild(we));
// Even add event listener later
wordElements.forEach(we => {
we.addEventListener("click", e => {
console.log(`Through el reference: ${we.innerHTML}`);
console.log(`Through currentTarget: ${e.currentTarget.innerHTML}`);
});
});
<div id="app"></div>
答案 1 :(得分:0)
您需要将新的li元素推入数组(在我的示例中为lis
)
var $ul = document.querySelector('.maldito');
var $li = $ul.querySelectorAll('li');
let lis = [];// li elements array
(function(){
var x = 0;
while ( x < 2) {
x++;
var addLi = document.createElement('li');
$ul.appendChild(addLi);
lis.push(addLi);// push the li element into the lis array
}
// $li = $ul.querySelectorAll('li');
for ( var i = 0; i < lis.length; i++ ){
lis[i].textContent = "Some text";
}
window.addEventListener('DOMContentLoaded', function(){
//console.log(lis.length)
for ( var i = 0; i < lis.length; i++ ){
lis[i].addEventListener('click', function(){
this.classList.add('active');
})
}
})
})()
.active{color:red}
<div class="row">
<ul class="maldito mt-5">
</ul>
</div>