[英]Javascript for…of doesn't work in Safari
Currently I am trying to build a simple sidenavigation that appears/disappears whenever one of the "toggleSidenav" buttons is clicked (there are multiple). 目前我正在尝试建立一个简单的侧导航,只要点击其中一个“toggleSidenav”按钮(有多个)就会出现/消失。
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. 在使用Firefox和Chrome进行测试时似乎工作正常,但今天当我尝试使用Safari(桌面和移动版)打开我的页面时,按钮没有做任何事情。
The problem seems to be the for-of-loop I used but checking the reference of the for...of , Safari should support it. 问题似乎是我使用的循环,但检查for ...的引用 ,Safari应该支持它。
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. 我可能还需要使用另一种方法,因为for ...只能由IE / Edge 12+支持,但我仍然想知道为什么这不起作用。
Safari supports for-of
with arrays. Safari支持
for-of
与阵列。 getElementsByClassName
returns a NodeList
, which is array-like, but isn't a true array, so you need to convert it to an array. getElementsByClassName
返回一个NodeList
,它类似于数组,但不是真正的数组,因此您需要将其转换为数组。 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-of
支持ECMAScript 6,因此可以使用Array.from()
进行此转换,而不是像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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.