无法为新创建的 div

问题描述

我无法 setAttribute() 甚至 createAttribute() 将 className 添加到新创建的 div 元素。值得注意的是,div 是使用 fetch().then() 命令在 createElement 链内创建的。代码看起来像这样...

document.addEventListener("DOMContentLoaded",() => {
    let row = 0
    fetch(domain + "/boards/new")
        .then(resp => resp.json())
        .then(json => json.spaces)
        .then(spaces => spaces.forEach( (iRow) => {
            let col = 0
            iRow.forEach( (iCol) => {
                if (iCol != null){
                    let checker = document.createElement('div')
                    let color = iCol.team
                    let c_id = iCol.id
                    checker.createAttribute(className)
                    checker.setAttribute(className,`${color}-checker`)
                    checker.createAttribute(id)
                    checker.setAttribute(id,c_id)
                    checker.createAttribute(data-pos)
                    checker.setAttribute(data-pos,`[${row}][${col}]`)
                    document.body.appendChild(checker)
                }
                col = col + 1
            })
            row = row + 1
        }))
})

它一直到 checker.createAttribute(className) 行,但随后出错,说“className is note defined”这很奇怪,编译器应该将 className 理解为全局 HTML 属性,不是吗?

解决方法

https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute

文档提到 createAttribute() 方法的参数接受一个字符串参数,因此当您收到 className not defined 错误时,似乎是因为它正在尝试查找字符串存储在 className