在下面的html元素中,当动态显示的那些html内容click事件尚不起作用时,它们将静态呈现。
var toggler = document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
/* Remove default bullets */
ul, .myUL {
list-style-type: none;
}
/* Remove margins and padding from the parent ul */
.myUL {
margin: 0;
padding: 0;
}
/* Style the caret/arrow */
.caret {
cursor: pointer;
user-select: none; /* Prevent text selection */
}
/* Create the caret/arrow with a unicode, and style it */
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
}
/* Rotate the caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
transform: rotate(90deg);
}
<pre><code>
/* Hide the nested list */
.nested {
display: none;
}
/* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
.active {
display: block;
}
<ul id="myUL">
<li><span class="caret">Beverages</span>
<ul class="nested">
<li>Water</li>
<li>Coffee</li>
<li><span class="caret">Tea</span>
<ul class="nested">
<li>Black Tea</li>
<li>White Tea</li>
<li><span class="caret">Green Tea</span>
<ul class="nested">
<li>Sencha</li>
<li>Gyokuro</li>
<li>Matcha</li>
<li>Pi Lo Chun</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
最佳答案
您的事件监听器的问题在于它将无法在动态创建的内容上运行。它绑定到仅在首次添加事件侦听器时存在的元素。
您可以从文档中捕获事件,然后在事件与元素选择器匹配时对其进行处理:
document.addEventListener('click', function(e) {
if(e.target && e.target.classList.contains('caret')) {
e.target.parentElement.querySelector(".nested").classList.toggle("active");
e.target.classList.toggle("caret-down");
}
});
关于javascript - 使用列表项的树状 View ,但是click事件不适用于动态创建的HTML内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59370392/