首页 > 解决方案 > Javascript 显示“无法设置属性‘innerHTML’为空”

问题描述

我尝试运行以下显示空白屏幕的代码

function make() {
    for (var i = 1; i <= 8; i++) {
        var j = "d" + i;
        var c = document.createElement("div");
        c.setAttribute("id",j);
        document.getElementById(j).innerHTML = 'Hello<br>';
    }
}
#d1 {font-family: 'Cinzel';}
#d2 {font-family: 'Cookie';}
#d3 {font-family: 'Great Vibes';}
#d4 {font-family: 'Monoton';}
#d5 {font-family: 'Orbitron';}
#d6 {font-family: 'Pacifico';}
#d7 {font-family: 'Righteous';}
#d8 {font-family: 'Sacramento';}
<!DOCTYPE html>
<html>
<head>
<title>Logo</title>
<link href="https://fonts.googleapis.com/css?family=Cinzel|Cookie|Great+Vibes|Monoton|Orbitron|Pacifico|Righteous|Sacramento" rel="stylesheet">
</head>
<body onload="make()">
</body>
</html>

在上面的代码片段中,我使用了一个 javascript 函数,其中我创建了 8 个元素并用 line-break 分隔每个元素。但是,不幸的是,包含“innerHTML”的行会引发类型错误,并且其余代码不会生成所需的输出。
请帮帮我!
谢谢你

标签: javascripthtml

解决方案


你错过了这条非常重要的线document.body.appendChild(c);

您必须使用 appendChildor将元素插入到文档树中,insertBefore因为在尝试获取元素之前必须将元素插入到 DOM 中document.getElementById(j)

<!DOCTYPE html>
<html>

<head>
  <title>Logo</title>
  <link href="https://fonts.googleapis.com/css?family=Cinzel|Cookie|Great+Vibes|Monoton|Orbitron|Pacifico|Righteous|Sacramento" rel="stylesheet">
  <style type="text/css">
    #d1 {
      font-family: 'Cinzel';
    }
    
    #d2 {
      font-family: 'Cookie';
    }
    
    #d3 {
      font-family: 'Great Vibes';
    }
    
    #d4 {
      font-family: 'Monoton';
    }
    
    #d5 {
      font-family: 'Orbitron';
    }
    
    #d6 {
      font-family: 'Pacifico';
    }
    
    #d7 {
      font-family: 'Righteous';
    }
    
    #d8 {
      font-family: 'Sacramento';
    }
  </style>
</head>

<body onload="make()">
  <script type="text/javascript">
    function make() {
      for (var i = 1; i <= 8; i++) {
        var j = "d" + i;
        var c = document.createElement("div");
        c.setAttribute("id", j);
        document.body.appendChild(c);
        document.getElementById(j).innerHTML = 'Hello<br>';
      }
    }
  </script>
</body>

</html>


推荐阅读