开发者问题收集

我使用 javascript 创建了元素。如何将另一个元素附加到其中?

2022-04-26
67

我创建了一个绘制矩形的元素。我如何创建另一个元素来将玩家输入附加到其中?每当我尝试使用下面的代码附加时,它都会显示此错误:

Uncaught TypeError: Cannot read properties of null (reading 'appendChild') at HTMLButtonElement. (jscript.js:16:57)

提前致谢。

//Clicking a button will add another player into the counter.
let playerButton = document.getElementById("addPlayer")
let playerInput = document.getElementById("playerName");
let playerId = 0;

playerButton.addEventListener("click", function() {
  if (!playerInput.value) {
    alert("You have to write a name")
  } else {
    const active_player = document.createElement("div" + playerId)
    active_player.setAttribute("id", "act_player")
    const playerName = document.createElement("p")
    document.getElementById("players").appendChild(active_player)
    document.getElementById("active_player").appendChild(playerName.value)
    playerId++
    console.log(playerName)
  }
})
.group:after {
  content: "";
  display: table;
  clear: both;
}

body {
  width: 80em;
  margin: 0 auto;
}

.playerPick {
  text-align: center;
}

#act_player {
  display: inline-block;
  margin-left: 10px;
  margin-right: 10px;
  height: 40em;
  width: 25em;
  border: solid black 1px;
}
<div class="playerPick">
  <h1>UNO SCORE COUNTER</h1>
  <button id="addPlayer">Add Player</button>
  <input type="text" placeholder="Enter your name here" id="playerName">
</div>

<div id="players"></div>
2个回答

在此行中:

document.getElementById("active_player").appendChild(playerName.value)

您正在尝试获取 active_player 的 id,但您正在在此行创建一个具有 act_player id 的组件:

active_player.setAttribute("id", "act_player")

如果两个 id 匹配,它应该可以工作。

joaomlap
2022-04-26

您的代码中有一些拼写错误和逻辑错误。

我想,这就是您要找的。

let playerButton = document.getElementById("addPlayer")
let playerInput = document.getElementById("playerName");
let playerId = 0;

playerButton.addEventListener("click", function() {
  if (!playerInput.value) {
    alert("You have to write a name")
  } else {
    var active_player = document.getElementById("act_player");
    if (active_player === null) {
      active_player = document.createElement("div");
      active_player.setAttribute("id", "act_player");
    }
    const playerName = document.createElement("p");
    playerName.innerText = playerInput.value;
    document.getElementById("players").appendChild(active_player);
    document.getElementById("act_player").appendChild(playerName);
    playerId++;
  }
});
.group:after {
  content: "";
  display: table;
  clear: both;
}

body {
  width: 80em;
  margin: 0 auto;
}

.playerPick {
  text-align: center;
}

#act_player {
  display: inline-block;
  margin-left: 10px;
  margin-right: 10px;
  height: 40em;
  width: 25em;
  border: solid black 1px;
}
<div class="playerPick">
  <h1>UNO SCORE COUNTER</h1>
  <button id="addPlayer">Add Player</button>
  <input type="text" placeholder="Enter your name here" id="playerName">
</div>

<div id="players"></div>

Chirag
2022-04-26