【问题标题】:How do I fix "Cannot set property of undefined"? [closed]如何修复“无法设置未定义的属性”? [关闭]
【发布时间】:2021-02-04 22:24:18
【问题描述】:

当用户按下按钮时,我试图为我的可编辑 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: 无法设置未定义的属性“背景颜色”。

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

我什至完成了:

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

尽管风格不属于那里。

控制台返回: 类型错误:无法读取未定义的属性“样式”。

我该如何解决这个问题?

【问题讨论】:

  • Despite style not belonging there 如果你可以“链接”这样的方法,那么风格肯定属于那里......即document.getElementById("bio-content").style.backgroundColor = "green"; 是正确的,但document.getElementById("bio-content").backgroundColor = "green"; 不是

标签: javascript html methods typeerror console.log


【解决方案1】:
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";

【讨论】:

    猜你喜欢
    • 2020-07-19
    • 1970-01-01
    • 2019-12-13
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2019-12-08
    相关资源
    最近更新 更多