gpt4 book ai didi

javascript - 如何在 querySelectorAll 返回的伪数组上使用 forEach?

转载 作者:行者123 更新时间:2023-12-03 13:30:21 24 4
gpt4 key购买 nike

使用纯 javascript 的好处是能够使用 forEach , map , filter等,由 document.querySelectorAll 返回的项目, document.getElementsBy*等等

这将减少对 jQuery 的依赖,并且代码更简洁。现在,我们可以这样做,以一种丑陋的方式:

[].forEach.call( document.querySelectorAll(sel), function(el) {
});

这是……冗长的。

任何可以使用 forEach的方式并立即对返回的元素点赞?

最佳答案

如果您在 Chrome 上进行测试,一种天真的方法是这样做:

NodeList.prototype.forEach = Array.prototype.forEach;

这行得通。在 Webkit 上。但它不在 Firefox 上。因为 FF 返回一个 HTMLCollection...

我发现的最跨浏览器的方式:
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;

但它不适用于 IE8 及更低版本,因为它们在向宿主对象原型(prototype)添加属性时会阻塞。

完整列表:
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.map = HTMLCollection.prototype.map = Array.prototype.map;
NodeList.prototype.filter = HTMLCollection.prototype.filter = Array.prototype.filter;
NodeList.prototype.reduce = HTMLCollection.prototype.reduce = Array.prototype.reduce;
NodeList.prototype.reduceRight = HTMLCollection.prototype.reduceRight = Array.prototype.reduceRight;
NodeList.prototype.every = HTMLCollection.prototype.every = Array.prototype.every;
NodeList.prototype.some = HTMLCollection.prototype.some = Array.prototype.some;

或者,为了取悦我们亲爱的 Bergi(也因为它更干净):
['forEach', 'map', 'filter', 'reduce', 'reduceRight', 'every', 'some'].forEach(
function(p) {
NodeList.prototype[p] = HTMLCollection.prototype[p] = Array.prototype[p];
});

考虑到与完美杀戮的联系,它在那里几乎无关紧要。问题是 DOM 在扩展时在浏览器上的行为大多不一样。除 IE <=8 外,此修改在所有浏览器中都是合理的。

关于javascript - 如何在 querySelectorAll 返回的伪数组上使用 forEach?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13957354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com