您好我是编码的新手并且有一个通用的问题,我到处寻找并且无法找到解决方案。我正在关注一个javascript教程并遇到了这个特定的代码行。 childnode声明属性' backgroundColor'是不确定的,我不知道为什么。
错误:"未捕获的类型错误:无法设置属性' backgroundColor'未定义"
<!doctype html>
<html>
<head>
</head>
<body>
<div id = "sampDiv">
<p> This is a txt field </p>
<p> This is another txt field </p>
</div>
<script>
var sampDiv = document.getElementById("sampDiv");
sampDiv.childNodes[0].style.backgroundColor = "red";
</script>
</body>
</html>
答案 0 :(得分:2)
使用children[0]
代替childNodes[0]
:
https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children
var sampDiv = document.getElementById("sampDiv");
sampDiv.children[0].style.backgroundColor = "red";
&#13;
<!doctype html>
<html>
<head>
</head>
<body>
<div id = "sampDiv">
<p> This is a txt field </p>
<p> This is another txt field </p>
</div>
</body>
</html>
&#13;