javascript 项目中出现“无法设置null的属性”错误

lf5gs5x2  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(190)

我是一个js/html的新手,当我添加“document.getElementById”标记后出现此错误时,这个小项目即将完成。
这是显示控制台中错误的图像
x1c 0d1x和下面的是我写的函数和它引用的对象。

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"
        }
    }
};

看到多个stackof说对象需要在“getelementbyid”标签之上,已经这样做了,它仍然不起作用。

7eumitmz

7eumitmz1#

你需要声明对象 * 才能使用它们(即对象不会提升)。

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>

相关问题