为什么函数只给出第一个输入的值?

Why does the function only give the value of the first input?

每当我尝试点击颜色时,它只给出 "White",但不想在屏幕上给出其他值。

我不明白我在这里做错了什么。

var x = document.getElementById("mySelect").value;
function myFunction() {
  document.getElementById("text").innerHTML = "Achtergrondkleur is: " + x;
}
<table BORDER="4">
  <tr>
    <td colspan="2" class="kleur">Selecteer een kleur!</td>
  </tr>
  <tr class="radio">
    <td onchange="myFunction()">
      <input id="mySelect" value="Wit" type="radio" class="color">Wit <br>
      <input id="mySelect" value="Grijs" type="radio" class="color">Grijs <br>
      <input id="mySelect" value="Groen" type="radio" class="color">Groen <br>
      <input id="mySelect" value="Geel" type="radio" class="color">Geel <br>
      <input id="mySelect" value="Rood" type="radio" class="color">Rood <br>
      <input id="mySelect" value="Blauw" type="radio" class="color">Blauw <br>
      <input id="mySelect" value="Zwart" type="radio" class="color">Zwart <br>
    </td>
    <td>
      <div class="circle"></div>
    </td>
  </tr>
  <tr class="radio">
    <td colspan="2">
      <p id="text"></p>
    </td>
  </tr>
</table>

这一行

var x = document.getElementById("mySelect").value;

只会给你第一个元素,因为你为每个元素使用了相同的 ID。你必须给每个元素一个唯一的 ID。

您的代码存在一些问题:

  • id在页面中必须是唯一的,所以应该替换成name;
  • 您需要在 "mySelect" name.
  • 的元素中添加 click-event listener

document.getElementsByName("mySelect").forEach(mySelect => {
  mySelect.addEventListener("click", function() {
    if (this.checked) {
      document.getElementById("text").innerHTML = "Achtergrondkleur is: " + this.value;
    }
  });
});
<table BORDER="4">
  <tr>
    <td colspan="2" class="kleur">Selecteer een kleur!</td>
  </tr>
  <tr class="radio">
    <td>
      <input name="mySelect" value="Wit" type="radio" class="color">Wit <br>
      <input name="mySelect" value="Grijs" type="radio" class="color">Grijs <br>
      <input name="mySelect" value="Groen" type="radio" class="color">Groen <br>
      <input name="mySelect" value="Geel" type="radio" class="color">Geel <br>
      <input name="mySelect" value="Rood" type="radio" class="color">Rood <br>
      <input name="mySelect" value="Blauw" type="radio" class="color">Blauw <br>
      <input name="mySelect" value="Zwart" type="radio" class="color">Zwart <br>
    </td>
    <td>
      <div class="circle"></div>
    </td>
  </tr>
  <tr class="radio">
    <td colspan="2">
      <p id="text"></p>
    </td>
  </tr>
</table>