【问题标题】:Unable to get forEach to properly work on IE无法让 forEach 在 IE 上正常工作
【发布时间】:2019-04-09 15:21:55
【问题描述】:

我在我的代码中完成了一个活动/禁用功能,该功能在 Chrome/Firefox 上运行良好,但由于某种原因,我在使用 forEach 时在 IE 中遇到错误。

这是在 IE 上显示的错误:

在 Chrome 和 Firefox 上,div 突出显示该框,正确的框显示在下方。

这是我正在使用的代码:

"use strict";

var tabButtons = document.querySelectorAll('.navlinksGP > a');

function enableTabButton(buttonId) {
tabButtons.forEach(function(btn) {
if (btn.id === buttonId) {
  btn.disabled = true;
  btn.style.background = '#eeaf00';
    btn.style.color = '#ffffff';
} else {
  btn.disabled = false;
  btn.style.background = '#ffffff';
    btn.style.color = '#eeaf00';
}
});
}
    enableTabButton('word');

var player = document.getElementById('player');

function wButton(element) {
  enableTabButton(element);
  if (element === "word") {
    player.innerHTML = "<h1 id=\"h1update\">Brand & Consumer Marketing</h1>";
  }
<div class="navlinksGP">
   <a id="word" onclick="wButton(this.id); window.location='#container'" href="#">BRAND & CONSUMER MARKETING</a>
</div>

我在 IE 上的唯一问题是 enableTabButton 函数根本不起作用。

【问题讨论】:

  • 尝试使用forEach的每个函数

标签: javascript jquery html css arrays


【解决方案1】:

没有任何版本的 Internet Explorer 支持在 NodeList 上使用 forEach(),这是从 querySelectorAll() 返回的内容。

有一个 polyfill 可以解决这个问题:https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach#Polyfill

【讨论】:

【解决方案2】:

由于您已使用关键字“jQuery”标记问题,我将使用 jQuery 回答您的问题 :-) 如果这符合您的需要,请检查以下解决方案。在 IE11 以及所有其他更现代的浏览器中为我工作。

"use strict";

var tabButtons = document.querySelectorAll('.navlinksGP > a');

function enableTabButton(buttonId) {

  $(tabButtons).each(function() {

    //console.log($(this).attr("id"));

    if ($(this).attr("id") === buttonId) {
      $(this).prop("disabled", true);
      $(this).css("background-color", "#eeaf00");
      $(this).css("color", "#ffffff");
    } else {
      $(this).prop("disabled", false);
      $(this).css("background-color", "#ffffff");
      $(this).css("color", "#eeaf00");
    }

  });
}

enableTabButton('word');

var player = document.getElementById('player');

function wButton(element) {
  enableTabButton(element);
  if (element === "word") {
    player.innerHTML = "<h1 id=\"h1update\">Brand & Consumer Marketing</h1>";
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="navlinksGP">
   <a id="word" onclick="wButton(this.id); window.location='#container'" href="#">BRAND & CONSUMER MARKETING</a>
</div>

【讨论】:

  • JonShow,即使在 Windows 7 IE 11 上也能完美运行!非常感谢!出于某种原因,加载时“单词” div 不会突出显示,除非我单击它然后更改。你知道原因吗? enableTabbutton('word');被调用。
  • 搞清楚了:D
  • 很高兴能帮上忙!
猜你喜欢
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多