如何修复"Cannot set property of undefined"?



当用户按下按钮时,我正试图为我的可编辑div框设置背景颜色以更改,但当按下该按钮时,除背景颜色外的所有颜色都会更改:

function saveBio() {
let biography = document.getElementById("bio-content").innerHTML;
biography = localStorage.setItem('bio', biography);
let content = document.getElementById("bio-content").setAttribute("contenteditable", false).backgroundColor = "green";`
}

我得到错误:

TypeError:无法设置未定义的属性"backgroundColor"。

我在网上寻找了一个解决方案,甚至是关于这个问题的类似问题,但它们并没有真正帮助我。我做错了什么?为什么控制台显示为未定义?

我甚至做过:

let content = document.getElementById("bio-content").setAttribute("contenteditable", false).style.backgroundColor = "green";

尽管风格不属于那里。

控制台返回:TypeError:无法读取未定义的属性"style"。

我该怎么解决这个问题?

let content = document.getElementById("bio-content").setAttribute("contenteditable", false).backgroundColor = "green";`

这里的问题是,以下内容:

document.getElementById("bio-content").setAttribute("contenteditable", false)

将返回undefined,这将阻止您链接其他调用。

您可以保存元素引用,然后进行更改:

const element = document.getElementById("bio-content");
element.setAttribute("contenteditable", false)
element.style.backgroundColor = "green";

相关内容

最新更新