我使用以下代码迭代DOM元素的集合(如下所示:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Iterating_over_a_DOM_collection)
let articleParagraphs = document.querySelectorAll("article > p");
for (let paragraph of articleParagraphs) {
paragraph.classList.add("read");
}
如何检测我正在循环播放的集合中的哪个对象?最重要的是,当我正在查看最后一个对象时,我怎么知道?
答案 0 :(得分:3)
将变量设置为列表中的最后一个段落。
var lastParagraph = articleParagraphs[articleParagraphs.length-1];
for (let paragraph of articleParagraphs) {
paragraph.classList.add("read");
if (paragraph == lastParagraph) {
...
}
}