for of 循环querySelectorAll

for of loop querySelectorAll

Mozilla 表示 "for of loops will loop over NodeList objects correctly"。 (来源:https://developer.mozilla.org/en-US/docs/Web/API/NodeList)但是,这在 Chrome 中不起作用 43. 这是不正确的文档还是浏览器错误?

在带有复选框的页面上使用的复制示例代码:

var list = document.querySelectorAll( 'input[type=checkbox]' );
for (var item of list) {
  item.checked = true;
}

由于我已经在 Gecko 中成功地使用 for..of 来迭代 NodeLists,看来这是一个浏览器错误,或者至少是浏览器缺乏。

我目前使用的用户脚本的实际工作代码:

let llnk = document.querySelectorAll("div#threadlist a.threadtitle_unread");
for (let lnk of llnk) {
    //...
}

(这也使用了 let,但那是另外一回事了。)

文档是正确的,但我不会将其称为错误。而是 "not yet implemented feature".

这方面没有标准,关于 DOM 应该如何与 ES6 集成的问题仍在积极讨论中。请注意,很明显 that querySelectorAll 应该 return 可以在 for of 循环中使用的可迭代的东西(如常见的期望要求),但是不清楚如何应该发生(让NodeList实现Iterable接口?让一些Elements collection子类Array?)。

尝试利用 Array.prototype.entries()

var list = [].entries.call(document.querySelectorAll("input[type=checkbox]"));

for (item of list) {
  item[1].checked = true;
};
<input type="checkbox" /><input type="checkbox" />

您也可以使用 Array.prototype.values()

var list = [].values.call(document.querySelectorAll("input[type=checkbox]"));

for (item of list) {
  item.checked = true;
};
<input type="checkbox" /><input type="checkbox" />

编辑:This is shipping in Chrome 51.

Jake Archibald posted a simple fix:

NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator]

还有 for of 循环。

您可以使用Array.from

let _list = document.querySelectorAll('input[type=checkbox]');

let list = Array.from(_list);

for (let item of list) {
  //... just like an array
  item.checked = true
}

或更短时间

let list = document.querySelectorAll('input[type=checkbox]');

for (let item of Array.from(list)) {
  item.checked = true
}

重要说明 Array.from 已在 Chrome 45 source.

中介绍

这就是我所做的,不同的方法

Array.prototype.forEach.call(document.querySelectorAll("input[type=checkbox]"),function(ele,idx)
{
    ele.checked = true;
}

IE9 及以上版本良好

2014 年对 NodeList 的原生 Symbol.iterator 支持为 added to the WHATWG's DOM spec

不幸的是,Chrome 51 是第一个支持它的 Chrome 版本,在撰写此答案时其 Beta 才刚刚发布。此外,任何版本的 Internet Explorer 或 Edge 均不支持。

要在所有浏览器中为您的代码添加 Symbol.iteratorNodeList 的支持,只需使用以下 polyfill:

NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

这是现代的另一种解决方案:

[...document.querySelectorAll("input[type=checkbox]")].forEach(node => {
     node.textContent = "foo";
});

这利用了 spread operator which is supported in Google Chrome 46+, Firefox 16+, and Edge, and just for fun the arrow function

我遇到了这个问题。原来我的是通过使用参数而不是数组调用 Promise.all() 引起的。例如:

之前:Promise.all(p1, p2)

之后:Promise.all([p1, p2])

希望这对某人有所帮助。