[英]why do we write [0] in the code which i specified?
我们为什么要写(item.classList[0] === "complete-btn")
比如什么是"item.classList[0]"
,为什么这里是 0 [0]?
if(item.classList[0] === "complete-btn"){
const todo = item.parentElement;
todo.classList.toggle("completed");
}
}
classList
是元素上DOMTokenList
名称的 DOMTokenList。 您可以像使用 arrays 一样对列表进行索引,以访问列表中的各个令牌(在本例中为类)。 例如,如果你有class="abc"
,那么.classList[0]
是"a"
, .classList[1]
是"b"
, .classList[2]
是"c"
。 但是,请继续阅读。
问题中代码的作者认为查看列表中的第一个class 是否为complete-btn
是有意义的。 这是一种不好的做法,因为 class 列表中的类顺序并不重要,并且可以随着从列表中添加和删除类而改变。¹因此,最好使用contains
编写:
if (item.classList.contains("complete-btn")) {
对于带有class="example complete-btn"
的元素,原始代码会失败,而使用contains
的代码不会:
const item = document.querySelector(".example"); console.log(item.classList[0] === "complete-btn"); // false, [0] is "example" console.log(item.classList.contains("complete-btn")); // true
<div class="example complete-btn"></div>
¹ “这是一种不好的做法,因为 class 列表中的类顺序并不重要,并且随着从列表中添加和删除类,它可能会发生变化。” Granted, if complete-btn
is the first class listed in the class
attribute of the HTML and that class is never removed via .classList.remove
or .classList.toggle
, it will remain the first in the list; still, it's poor practice to rely on it, not least because someone maintaining the HTML could add another class at the beginning, not realizing the JavaScript was relying on order — because in general, there is no order to the classes in class
.
item.classlist
返回一个 DOMTokenList Object ,它就像一个数组,其中包含所有类。 在这里,我们从数组中访问它的第一个 class,这就是为什么为 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.