Javascript IE11 中的 JS ForEach 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47534102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:52:03  来源:igfitidea点击:

JS ForEach Loops in IE11

javascriptloopsinternet-explorerforeachinternet-explorer-11

提问by Steve Walker

I am having issues getting a JS loop to work over 4 elements on a page in IE11. I want the function hideImgto run on mouseover on the element that you hovered over.

我在让 JS 循环在 IE11 中的页面上处理 4 个元素时遇到问题。我希望该函数hideImg在鼠标悬停在您悬停的元素上时运行。

Here is my code:

这是我的代码:

elements.forEach( function(element) {
    element.addEventListener('mouseover', hideImg);
});

I think I've found that forEachloops are not supported in IE, how can I easily convert this to a forloop in plain JS?

我想我发现forEachIE 不支持循环,如何轻松地将其转换为for纯 JS 中的循环?

Kind regards,
Steve

亲切的问候,
史蒂夫

回答by Nemani

You can do it like this:

你可以这样做:

var elements = document.getElementsByClassName("test");
for (var i = 0; i < elements.length; i++) {
  elements[i].addEventListener('mouseover', hideImg);
}

function hideImg() {
  console.log("hideImg called")
}
.test {
  width: 40px;
  height: 20px;
  border: green solid 1px;
}
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

回答by Shailendra Dobhal

This code will fix your issue in IE 11.

此代码将解决您在 IE 11 中的问题。

Array.prototype.slice.call(elements).forEach( function(element) {
    element.addEventListener('mouseover', hideImg);
});

回答by Vince Sanchez Ta?an

Just add this to your code at the top of itthe code provided is supported in all Browsers

只需将此添加到您的代码顶部,所有浏览器都支持提供的代码

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
  }

if (!Array.prototype.forEach) {
 Array.prototype.forEach = function (callback, thisArg) {
 thisArg = thisArg || window;

for (var i = 0; i < this.length; i++) {
   callback.call(thisArg, this[i], i, this);
  }
 };
}

回答by Mike Godin

Can also use the somewhat more compact:

也可以使用稍微紧凑一些的:

Array.prototype.forEach.call(elements, function(element) {
    element.addEventListener('mouseover', hideImg);
});