JS ForEach Loops in IE11

↘锁芯ラ 提交于 2019-12-01 14:08:52

问题


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

Here is my code:

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

I think I've found that forEach loops are not supported in IE, how can I easily convert this to a for loop in plain JS?

Kind regards,
Steve


回答1:


Just follow basic programming

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>



回答2:


This code will fix your issue in IE 11.

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


来源:https://stackoverflow.com/questions/47534102/js-foreach-loops-in-ie11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!