无法读取null的属性“ setAttribute”-Javascript

时间:2019-01-17 17:06:57

标签: javascript getelementbyid

我在这里看到了几个与此错误有关的问题,并且看到了一些答案,我注意到普遍的共识是这是由于尚未创建DOM引起的。我尝试了几种不同的解决方案来修复它,例如将脚本移动到标记之前,在图像创建之前和之后使用日志输出,以确保实际上正确地创建了对象,但是没有任何事情可以解决我的问题。我是Java语言的新手,所以我可能很想念它吗?

var dice = [6, 6, 6, 6, 6];

function rollDice() {
  for (var i = 0; i < dice.length; ++i) {
    var num = Math.floor(Math.random() * 6 + 1);
    dice[i] = 1;
    document.write(dice[i] + "<br>");
  }
  for (var i = 0; i < dice.length; ++i) {
    var value = dice[i];
    var path;
    var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
    path = ArrayImage[value];
  }
  document.getElementById("dice_1").setAttribute("src", path)
}
<html>

<head>

  <meta charset="utf-8">
  <title>Project 1</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
  <h1> This is a javascript application</h1>
  <script>
    console.log("script #1: %o", document.getElementById("dice_1")); // null
  </script>
  <div>
    <img id="dice_1" src="images/dice 1.png">
    <img id="dice_2" src="images/dice 1.png">
    <img id="dice_3" src="images/dice 1.png">
    <img id="dice_4" src="images/dice 1.png">
    <img id="dice_5" src="images/dice 1.png">
  </div>
  <input id="but" type="button" onclick="rollDice()" value="Roll Dice.">
  <script>
    console.log("script #1: %o", document.getElementById("dice_1")); // null
  </script>
  <script type="text/javascript" src="scripts/script.js"></script>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

由于在加载文档后使用document.write,因此会清除整个文档(由于调用document.open())。因此,不存在要针对它们运行setAttribute的img元素。尝试以下操作(请注意由于数组索引从零开始,因此需要进行索引更正):

var dice = [6,6,6,6,6];
var results;
var resultsContainer = document.querySelector('.results');

function rollDice(){
    // clear results array
    results = [];
    for(var i =0; i<dice.length; ++i){
        var num = Math.floor(Math.random()*6 +1);
        dice[i] = num;
        results.push(dice[i]);
    }
    for(var i =0; i< dice.length; ++i){
        var value = dice[i];
        var path;
        var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3.png", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
        path = ArrayImage[value - 1];
        document.getElementById("dice_"+ (i + 1)).setAttribute("src",path);
    }
    // convert results array to text with <br> between them
    var resultsStr = results.join("<br>");
    // display results as text to page
    resultsContainer.innerHTML = resultsStr;
}