问题描述
我正在制作一个关于产品(颜色等)的选择的脚本,除了 Internet Explorer (11)& Edge 。
I am making a script for choices about a product (colors etc), which works in every browser except for Internet Explorer (11) & Edge.
我将每个参数的选项放在一个数组中,并使用数组向它们应用一个函数。 forEach()
方法。
I put the choices of each parameter in a array and apply a function to them with the array.forEach()
method.
颜色参数示例:
var color_btns = document.querySelectorAll('#color > p');
color_btns.forEach(function(color) {
color.onclick = function () {
color_btns.forEach(function(element) {
if (element.classList.contains('selected')) {
element.classList.remove('selected');
}
});
color.classList.add('selected');
document.querySelector('#f_color').value = color.dataset.id;
};
});
我在 IE &的控制台中得到以下输出 Edge :
I get the following output in the console of both IE & Edge:
在搜索了这个问题之后,我了解到这个函数应该是支持。我试图自己定义功能但没有成功。当我记录该函数时,它被定义为一个函数(里面有 [native code]
。
After searching about the issue, I learnt that this function should be supported by IE 9 and newer. I tried to define the function by myself without success. When I log the function it is defined as a function (with "[native code]
" inside).
我用替换每个
,它运作良好, .forEach
I replaced every .forEach
by a for
and it's working pretty well,
- 但我怎样才能使它工作?
- 是否有特定用途的
forEach()
for Internet Explorer & Edge ?
- but how can I make it work ?
- Is there a specific usage of the
forEach()
for Internet Explorer & Edge ?
我认为它是 Array.prototype.forEach
以及IE的最近版本(以及Edge的所有版本)都有...?
I thought it was Array.prototype.forEach
and that recent versions of IE (and all versions of Edge) had it...?
推荐答案
返回不是数组,它是。最近才得到 forEach
(以及与JavaScript的迭代协议的兼容性,让你将它们用作的目标for-of
和点差表示法。
The return value of querySelectorAll
isn't an array, it's a NodeList. That only recently got forEach
(and compatibility with JavaScript's iteration protocol, letting you use them as the targets of for-of
and spread notation).
您可以轻松地将 forEach
填充:
if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) {
// Yes, there's really no need for `Object.defineProperty` here
NodeList.prototype.forEach = Array.prototype.forEach;
}
在这种情况下直接分配是正常的,因为可枚举
,可配置
,可写
应该都是 true
并且它是一个值属性。 (可枚举
true
让我感到惊讶,但这就是它在Chrome,Firefox,Edge和Safari上本地定义的方式)。
Direct assignment is fine in this case, because enumerable
, configurable
, and writable
should all be true
and it's a value property. (enumerable
being true
surprised me, but that's how it's defined natively on Chrome, Firefox, Edge, and Safari).
这篇关于forSeach querySelectorAll在最近的Microsoft浏览器中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!