提问人:Adithya Suresh 提问时间:4/9/2023 最后编辑:JMPAdithya Suresh 更新时间:4/9/2023 访问量:50
项目中出现“无法设置 null 的属性”错误
"Cannot set properties of null" error in project
问:
我是 js/html 的新手,当我添加“document.getElementById”标签后出现此错误时,这个小项目即将完成。
这是显示控制台中错误的图像
以下是 im 编写的函数和它所引用的对象。
for(const key1 in reservedSeats){
if(reservedSeats.hasOwnProperty(key1)){
const obj=reservedSeats[key1];
console.log(obj.seat)//checking to see if it returns the seat number
document.getElementById(obj.seat).className="r";
document.getElementById(obj.seat).innerHTML='R';
}
}
var reservedSeats = {
record1: {
seat: "b19",
owner: {
fname: "Joe",
lname: "Smith"
}
},
record2: {
seat: "b20",
owner: {
fname: "Joe",
lname: "Smith"
}
},
record3: {
seat: "b21",
owner: {
fname: "Joe",
lname: "Smith"
}
},
record4: {
seat: "b22",
owner: {
fname: "Joe",
lname: "Smith"
}
}
};
看到多个堆栈说对象需要在“getElementById”标签上方,已经这样做了,但它仍然不起作用。
答:
0赞
JMP
4/9/2023
#1
您需要先声明对象,然后才能使用它们(即对象不会提升)。
var reservedSeats = {
record1: {
seat: "b19",
owner: {
fname: "Joe",
lname: "Smith"
}
},
record2: {
seat: "b20",
owner: {
fname: "Joe",
lname: "Smith"
}
},
record3: {
seat: "b21",
owner: {
fname: "Joe",
lname: "Smith"
}
},
record4: {
seat: "b22",
owner: {
fname: "Joe",
lname: "Smith"
}
}
};
for(const key1 in reservedSeats) {
const obj=reservedSeats[key1];
document.getElementById(obj.seat).className="r";
document.getElementById(obj.seat).innerHTML='R';
}
td {width:20px;height:20px;background-color:green}
.r {background-color:red}
<table>
<tr><td id="a19"></td><td id="a20"></td></tr>
<tr><td id="a21"></td><td id="a22"></td></tr>
<tr><td id="b19"></td><td id="b20"></td></tr>
<tr><td id="b21"></td><td id="b22"></td></tr>
<tr><td id="c19"></td><td id="c20"></td></tr>
<tr><td id="c21"></td><td id="c22"></td></tr>
</table>
评论