JavaScript中的getElementsByClassName().forEach()函数无法工作

4

我正在尝试通过JavaScript按类名获取HTML的每个元素,然后根据range对象onchange中的值更改其高度和宽度。

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

但是我已经尝试了所有可能的结构,仍然没有效果。

这是我的第一段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>';

你可以在这个问题中了解更多关于HTML集合的内容。 - Flimtix
1个回答

12
浏览器出现错误: document.getElementsByClassName(...).forEach 不是一个函数。
这是因为getElementsByClassName不返回数组,而是返回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添加到HTMLCollection中,您可以在任何近代浏览器(甚至是IE8,如果您先使用Array.prototype.forEach填充)上像这样做:
if (typeof HTMLCollection !== "undefined" && HTMLCollection.prototype && !HTMLCollection.prototype.forEach) {
    Object.defineProperty(HTMLCollection.prototype, "forEach", {
        value: Array.prototype.forEach,
        configurable: true,
        writable: true
    });
}

最后,需要注意的是,HTMLCollection 没有 forEach 方法,但是由 querySelectorAll 返回的 NodeList 有,尽管在一些旧的浏览器上可能需要进行 polyfill。如果必要,请参见 this answer 关于 polyfilling NodeList

更多:


太棒了,非常感谢。一直以来我都认为 getElementsByClassName 创建的是一个数组。 - Jousi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接