问题
This code is not working in Edge browser. The accordion panel does not open and I get this error:
Object doesn't support property or method 'forEach'
const accordionBtn = document.querySelectorAll('.btn-accordion');
accordionBtn.forEach(item => item.addEventListener('click', e => {
e.preventDefault();
const currItem = e.currentTarget;
currItem.classList.toggle("open");
}))
回答1:
Note this should work in Edge 16+ and across the latest versions of other browsers according to MDN. I manually tested Edge 17 and verified it works there.
Workaround
The issue stems from the fact that querySelectorAll
returns a NodeList
instead of an Array
in all browsers. While Array
has supported forEach
for some time, only more recently has the API been added to NodeList
.
If you want to use this and need to support older browser versions, you can create a trivial polyfill by copying the implementation from Array
itself (works in IE9+):
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
What about filter
and map
?
Also worth noting is that a number of other helpful APIs like filter
and map
still do not exist on NodeList
in any browser. Therefore if you want the full experience, your best bet is to copy the items into a real Array
.
In most modern browsers this can be done using Array.from(nodelist) or via the spread syntax [...nodelist]
. However, if you need to support IE you can use slice
(among other creative techniques) to get the job done:
var arr = Array.prototype.slice.call(nodelist);
回答2:
This variant works!
const accordionBtn = document.querySelectorAll('.btn-accordion');
[...accordionBtn].forEach(item => item.addEventListener('click', e => {
e.preventDefault();
const currItem = e.currentTarget;
currItem.classList.toggle("open");
}))
来源:https://stackoverflow.com/questions/51824545/why-is-foreach-not-working-in-edge