Node.childNodes的forEach方法是什么?

13

在回答一个关于Node.childNodes.item()属性问题时,我提供了错误的答案。后来我检查了form元素返回的childNodes__proto__,发现了一个forEach方法。请参考Node.childNodes

Node.childNodesforEach方法在NodeList规范、MDN的Methods接口NodeList中均未被记录,并且似乎没有在使用forEach方法迭代NodeList或链接到该问题的页面中提到;尽管它在Chromium 50中可用。

这个方法只能在相对较新的Chrome / Chromium版本中使用吗?如果是,这是否有文档记录?

关于Node.childNodesforEach()方法是否有任何文档记录?


document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault();
  var form = e.target;
  form.childNodes.forEach(function(el) {
    if (el.tagName === "INPUT" && el.type !== "submit")
      snippet.log("name:" + el.name + ", value:" + el.value)
  });
});
<form>
  <input type="text" name="firstName" value="The first name">
  <input type="text" name="lastName" value="The last name">
  <input type="email" name="emailAddress" value="email@example.com">
  <br>
  <input type="submit" value="Submit">
</form>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

2个回答

9

现在DOM4将 NodeList 定义为可迭代对象:

iterable<Node>;

根据IDL草案,这意味着:

An interface can be declared to be iterable by using an iterable declaration (matching Iterable) in the body of the interface.

iterable<value-type>;
iterable<key-type, value-type>;

Objects implementing an interface that is declared to be iterable support being iterated over to obtain a sequence of values.

Note: In the ECMAScript language binding, an interface that is iterable will have “entries”, “forEach”, “keys”, “values” and @@iterator properties on its interface prototype object.

If a single type parameter is given, then the interface has a value iterator and provides values of the specified type.


5

这种方法只在较新版本的Chrome / Chromium中可用吗?如果是,有相应的文档吗?

是的,这是DOM4中的新内容,因此并不普及。

有关Node.childNodes的forEach()方法是否有任何文档?

请参见Chromium bug跟踪器上的添加对[ArrayClass]的支持,并在NodeList上使用它

来自https://bugs.webkit.org/show_bug.cgi?id=81573

http://dom.spec.whatwg.org/#interface-nodelist

DOM4将NodeList规范为其原型链中具有Array.prototype。

这个还需要一些背景。 [ArrayClass]允许我们做类似document.querySelectorAll('.foo')。patch bugs.webkit.org带有运行时标志,因为目前是否仍然可以实现这一点尚不清楚。

从历史上看,这些类似数组的对象没有包含来自数组原型的这些方法,导致出现像Array.prototype.forEach.call(nodeList, function() { ... })的代码。这在DOM4中现在应该改变了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接