Javascript for…of doesn't work in Safari

落花浮王杯 提交于 2020-01-13 12:06:57

问题


Currently I am trying to build a simple sidenavigation that appears/disappears whenever one of the "toggleSidenav" buttons is clicked (there are multiple).

It seemed to work fine when testing with Firefox and Chrome but today when I tried to open my page with Safari (desktop and mobile version) the buttons didn't do anything.

The problem seems to be the for-of-loop I used but checking the reference of the for...of, Safari should support it.

My code:

for (var btn of document.getElementsByClassName("toggleSidenav")) {
    btn.addEventListener("click", function() {
        var style = window.getComputedStyle(document.getElementById("sidenav"));

        if (style.getPropertyValue("display") == "none") {
            openSidenav();
        } else {
            closeSidenav();
        }
    });
}

I probably need to use an alternative method anyway because the for...of is only supported by IE/Edge 12+ but I would still like to know why this didn't work.


回答1:


Safari supports for-of with arrays. getElementsByClassName returns a NodeList, which is array-like, but isn't a true array, so you need to convert it to an array. Since you're requiring ECMAScript 6 support for for-of, you can use Array.from() for this conversion, rather than some old idioms like Array.prototype.slice.call().

for (var btn of Array.from(document.getElementsByClassName("toggleSidenav"))) {
  btn.addEventListener("click", function() {
    var style = window.getComputedStyle(document.getElementById("sidenav"));

    if (style.getPropertyValue("display") == "none") {
      openSidenav();
    } else {
      closeSidenav();
    }
  });
}

function openSidenav() {
  document.getElementById("sidenav").style.display = 'block';
}

function closeSidenav() {
  document.getElementById("sidenav").style.display = 'none';
}
<button class="toggleSidenav">
  Toggle 1
</button>
<button class="toggleSidenav">
  Toggle 2
</button>
<button class="toggleSidenav">
  Toggle 3
</button>
<div id="sidenav">
  Side Nav
</div>


来源:https://stackoverflow.com/questions/41388374/javascript-for-of-doesnt-work-in-safari

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