0

我无法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属性,不是吗?

4

1 回答 1

0

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

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

于 2021-06-11T01:39:43.440 回答