var nodes
= document
.querySelectorAll(className
);
这里a得到的是一个NodeList类型的一个实例; NodeList是一个类数组对象:与数组一样具有length与index属性,但本质是Object; 是下面这种形式
NodeList
{
0: [object HTMLDivElement
],
1: [object HTMLDivElement
],
....
}
该实例对象在低版本浏览器不支持forEach方法,会报错 类似下面这样的错误。
TypeError
: nodes
.forEach is not a
function.
(In
'nodes.forEach', 'nodes.forEach' is undefined
)
解决方式
原本代码
const nodes
= document
.querySelectorAll(className
);
nodes
.forEach((el
, idx
) => {
})
Array
.prototype
.forEach
.call(nodes
,(el
, idx
) => {
})
Array
.from(nodes
).forEach((el
, idx
) => {
})
本质都是让其能够使用真正的数组的forEach方法。