JavaScript 中的 getElementsByClassName().forEach() 函数不起作用

2024-03-19

我试图使用 JavaScript 通过类名获取 HTML 的每个元素,然后根据 a 中的值更改其高度和宽度range object onchange.

浏览器显示错误:document.getElementsByClassName(...).forEach is not a function

但我尝试以各种可能的方式构建它,但仍然一无所获。

这就是我的第一个 JavaScript 代码的样子:

function updateInput(val) {
    document.getElementById('valueInput').innerHTML=val; /*This is just to show the value to the user*/
    document.getElementsByClassName('oneResult').forEach(functio‌​n changeWidth(element) { element.style.width = val + 'px'; } );
    document.getElementsByClassName('oneResult').forEach(functio‌​n changeWidth(element) { element.style.height = val + 'px'; } );
}

然后我尝试了这个:

function updateInput(val) {
    document.getElementById('valueInput').innerHTML=val;
    function oneResultWH(element) {
        element.style.width = val + 'px';
        element.style.height = val + 'px';
    }
    document.getElementsByClassName('oneResult').forEach(oneResultWH);
}

但仍然没有运气。

这就是我的 PHP 的样子:

print '<div class="oneResult" style="background-image:url(Pictures/'.$img.'); height: 100px; width:100px; ">
<a id="word'. $x .'">'. $textConversion[$x] .'</a></div>';

浏览器显示错误: document.getElementsByClassName(...).forEach 不是函数

那是因为getElementsByClassName不返回数组,它返回一个HTMLCollection https://dom.spec.whatwg.org/#htmlcollection。他们没有forEach方法(还;可能在某个时候,也可能不会)。

您可以像这样使用数组所具有的:

Array.prototype.forEach.call(document.getElementsByClassName("oneResult"), function(element) {
    // Use `element` here
});

或者在现代浏览器(或使用polyfill)上,您可以从集合中创建一个数组:

Array.from(document.getElementsByClassName("oneResult")).forEach(function(element) {
    // Use `element` here
});

另一种选择是添加forEach to HTMLCollection,你可以在任何模糊现代的浏览器上这样做(甚至是 IE8,如果你用 polyfillArray.prototype.forEach first):

if (typeof HTMLCollection !== "undefined" && HTMLCollection.prototype && !HTMLCollection.prototype.forEach) {
    Object.defineProperty(HTMLCollection.prototype, "forEach", {
        value: Array.prototype.forEach,
        configurable: true,
        writable: true
    });
}

最后,请注意,虽然HTMLCollection没有forEach, the NodeList由返回querySelectorAll确实如此,尽管在某些较旧的浏览器上可能需要进行多填充。看这个答案 https://stackoverflow.com/questions/46929157/foreach-on-queryselectorall-not-working-in-recent-microsoft-browsers/46929259#46929259关于聚填充NodeList如果需要的话。

More:

  • JavaScript 中的 For-each 数组? https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript(那里的一些答案 - 包括我的 - 有一个关于“类似数组”的东西的部分,其中包括HTMLCollections)
  • querySelectorAll、getElementsByClassName 和其他 getElementsBy* 方法返回什么? https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 中的 getElementsByClassName().forEach() 函数不起作用 的相关文章

随机推荐