forEach 适用于 querySelectorAll,但不适用于 getElementsByTagName?
forEach works on querySelectorAll, but not getElementsByTagName?
在编写代码时,我遇到了一些很奇怪的事情。
以下代码工作正常:
document.querySelectorAll("button").forEach(function(e) {
e.addEventListener("click", function() {
console.log(e);
});
});
但是,以下情况不会:
document.getElementsByTagName("button").forEach(function(e) {
e.addEventListener("click", function() {
console.log(e);
});
})
我在这里很困惑。据我所知,document.getElementsByTagName("button")
returns 与 document.querySelectorAll("button")
完全相同的数组。我错了吗?这里有什么问题?跟forEach
有关系吗?
旁注:
我遇到了 this post 但它没有回答我的问题。
只是强调:我没有使用 jQuery。
P.S。 - 我已经知道 forEach
与常规 for
循环之间的区别和优缺点,所以除非 forEach
是这两个函数不以相同方式工作的具体原因,否则forEach
vs for
辩论与我的问题无关。
区别在于从这些方法返回的内容。 querySelectorAll
returns a NodeList while getElementsByTagName
returns a HTMLCollection. None of them support the generic Array.forEach but NodeList implements its own NodeList.forEach 这就是你在这里点击的内容。
在编写代码时,我遇到了一些很奇怪的事情。
以下代码工作正常:
document.querySelectorAll("button").forEach(function(e) {
e.addEventListener("click", function() {
console.log(e);
});
});
但是,以下情况不会:
document.getElementsByTagName("button").forEach(function(e) {
e.addEventListener("click", function() {
console.log(e);
});
})
我在这里很困惑。据我所知,document.getElementsByTagName("button")
returns 与 document.querySelectorAll("button")
完全相同的数组。我错了吗?这里有什么问题?跟forEach
有关系吗?
旁注:
我遇到了 this post 但它没有回答我的问题。
只是强调:我没有使用 jQuery。
P.S。 - 我已经知道 forEach
与常规 for
循环之间的区别和优缺点,所以除非 forEach
是这两个函数不以相同方式工作的具体原因,否则forEach
vs for
辩论与我的问题无关。
区别在于从这些方法返回的内容。 querySelectorAll
returns a NodeList while getElementsByTagName
returns a HTMLCollection. None of them support the generic Array.forEach but NodeList implements its own NodeList.forEach 这就是你在这里点击的内容。