如何使用 JavaScript 在特定单选按钮上应用条件

How to apply Condition on specific Radio Button using JavaScript

我想要的是当我点击特定的 red id 单选按钮然后它显示 Alert 正如你在代码中看到的......在我的情况下它没有发生......问题是什么,我该如何解决?

<form>
  What color do you prefer?<br>
  <input type="radio" name="colors" id="red">Red<br>
  <input type="radio" name="colors" id="blue">Blue
</form>
<script>
  if (document.getElementById("red").checked == true) {
    alert('working');
  }
</script>

这样试试:

<form>
  What color do you prefer?<br>
  <input type="radio" name="colors" id="red"/>Red<br>
  <input type="radio" name="colors" id="blue"/>Blue
</form>
<script>
document.getElementById("red").onchange = function() {
   alert('working');
}
</script>

单击单选按钮时,需要一个事件处理程序来运行该特定代码。

您需要一个事件监听器

document.getElementById("red").addEventListener("change", myAlert); 

function myAlert() {
    alert('working');
}
<form>
    What color do you prefer?<br>
    <input type="radio" name="colors" id="red">Red<br>
    <input type="radio" name="colors" id="blue">Blue
</form>

  1. 您需要事件侦听器 - 不推荐使用内联事件处理程序
  2. 您需要决定要测试的内容

这里有两种方法运行

它们是收音机,所以我们不需要测试它们是否被选中

window.addEventListener("load",function() { // when the page loads

  // testing clicking the RED only
  document.getElementById("red").addEventListener("click",function() {
    console.log("The specific Red event listener was invoked");
  });    

  // delegation
  document.querySelector("form").addEventListener("click",function(e) {
    const tgt = e.target;
    if (tgt.id==="red") console.log("Clicking in the form, we clicked the thing with ID red")
  })
});
<form>
  What color do you prefer?<br>
  <label><input type="radio" name="colors" id="red">Red</label><br>
  <label><input type="radio" name="colors" id="blue">Blue</label>
</form>