微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法为新创建的 div

如何解决无法为新创建的 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。