我有一些 HTML 代码,如下所示:
<html><head></head><body>
<span class="cls1">test</span>
<span class="cls1">test</span>
<span class="cls1">test</span>
<span class="cls1">test</span>
<span class="cls1">test</span>
<span class="cls1">test</span>
<span class="cls1">test</span>
<style>
.cls1 {
color: red;
}
</style>
</body></html>
然后我想使用一些 JavaScript 代码来切换cls1这些元素的类。我输入了这些行。输出也如下:
> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.toggle("cls1") }
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
false
> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.toggle("cls1") }
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
false
> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.toggle("cls1") }
<span class="cls1">
debugger eval code:1:65
false
> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.add("cls1") }
undefined
> for (elem of document.getElementsByTagName("span")) { console.log(elem); elem.classList.add("cls1") }
<span class="">
debugger eval code:1:63
<span class="">
debugger eval code:1:63
<span class="">
debugger eval code:1:63
<span class="">
debugger eval code:1:63
<span class="">
debugger eval code:1:63
<span class="">
debugger eval code:1:63
<span class="">
debugger eval code:1:63
undefined
> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); }
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
<span class="cls1">
debugger eval code:1:65
undefined
我认为错误的是,document.getElementsByClassName可以找到所有七个元素,但elem.classList.toggle只适用于其中的一半。这对我来说是一个荒谬的问题。这里出了什么问题?
子衿沉夜
相关分类