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

我想要的是,当我单击特定的红色id 单选按钮时,它会向我显示警报,正如您在代码中看到的那样...在我的情况下,它没有发生...问题是什么以及如何对此进行排序?


<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>


慕森卡
浏览 141回答 3
3回答

慕田峪7331174

你需要一个事件监听器document.getElementById("red").addEventListener("change", myAlert);&nbsp;function myAlert() {&nbsp; &nbsp; alert('working');}<form>&nbsp; &nbsp; What color do you prefer?<br>&nbsp; &nbsp; <input type="radio" name="colors" id="red">Red<br>&nbsp; &nbsp; <input type="radio" name="colors" id="blue">Blue</form>

繁星点点滴滴

您需要事件侦听器 - 不建议使用内联事件处理程序您需要决定要测试什么这里有两种跑步方式它们是收音机,所以我们不需要测试它们是否被检查window.addEventListener("load",function() { // when the page loads&nbsp; // testing clicking the RED only&nbsp; document.getElementById("red").addEventListener("click",function() {&nbsp; &nbsp; console.log("The specific Red event listener was invoked");&nbsp; });&nbsp; &nbsp;&nbsp;&nbsp; // delegation&nbsp; document.querySelector("form").addEventListener("click",function(e) {&nbsp; &nbsp; const tgt = e.target;&nbsp; &nbsp; if (tgt.id==="red") console.log("Clicking in the form, we clicked the thing with ID red")&nbsp; })});<form>&nbsp; What color do you prefer?<br>&nbsp; <label><input type="radio" name="colors" id="red">Red</label><br>&nbsp; <label><input type="radio" name="colors" id="blue">Blue</label></form>

繁花不似锦

尝试这样:<form>&nbsp; What color do you prefer?<br>&nbsp; <input type="radio" name="colors" id="red"/>Red<br>&nbsp; <input type="radio" name="colors" id="blue"/>Blue</form><script>document.getElementById("red").onchange = function() {&nbsp; &nbsp;alert('working');}</script>单击单选按钮时需要一个事件处理程序来运行该特定代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript