为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕森卡 2023-07-20 17:39:56
我想要的是,当我单击特定的红色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>
查看完整描述

3 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

你需要一个事件监听器


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>


查看完整回答
反对 回复 2023-07-20
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

  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>


查看完整回答
反对 回复 2023-07-20
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

尝试这样:


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

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



查看完整回答
反对 回复 2023-07-20
  • 3 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信