You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:DOM加载后执行的JavaScript forEach循环代码无效,控制台运行正常

问题原因

document.getElementsByName()返回的是HTMLCollection类数组对象,它本身并没有内置的forEach方法,这就是页面脚本中循环无法执行的核心原因。

而浏览器控制台里,部分现代浏览器(如Chrome)会为HTMLCollection扩展forEach方法,所以你把相同代码放到控制台时能正常运行。

解决方案

以下几种方法都能解决这个问题:

方法1:用Array.from()转换为数组

window.onload = (event) => {
    var checkboxes = document.getElementsByName("plates")
    var labelPlate = document.getElementsByName("labelPlate")

    Array.from(checkboxes).forEach((i, index) => {
        if (i.checked) {
            labelPlate[index].classList.add("active")
        } else {
            labelPlate[index].classList.remove("active")
        }
    })
};

方法2:通过Array.prototype.forEach.call()调用forEach

window.onload = (event) => {
    var checkboxes = document.getElementsByName("plates")
    var labelPlate = document.getElementsByName("labelPlate")

    Array.prototype.forEach.call(checkboxes, (i, index) => {
        if (i.checked) {
            labelPlate[index].classList.add("active")
        } else {
            labelPlate[index].classList.remove("active")
        }
    })
};

方法3:用普通for循环替代forEach

window.onload = (event) => {
    var checkboxes = document.getElementsByName("plates")
    var labelPlate = document.getElementsByName("labelPlate")

    for (let index = 0; index < checkboxes.length; index++) {
        const checkbox = checkboxes[index];
        if (checkbox.checked) {
            labelPlate[index].classList.add("active")
        } else {
            labelPlate[index].classList.remove("active")
        }
    }
};

内容的提问来源于stack exchange,提问作者Victor França

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 08:40:03