5

您好,我是编码新手,有一个通用问题,我到处找,找不到解决方案。我正在关注一个 javascript 教程,并遇到了这行特定的代码。子节点声明属性“背景颜色”未定义,我不知道为什么。

错误:“未捕获的类型错误:无法设置未定义的属性‘背景颜色’”

<!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>
4

1 回答 1

4

使用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";
<!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>

于 2018-04-10T04:03:01.520 回答