繁体   English   中英

触发按钮选择单选按钮时单击

[英]Trigger Button Click when Radio button is selected

我有两个单选按钮,当我选择一个单选按钮(例如:id =一个)时,单击按钮将显示警报(“一个”)。 这是我的代码

<input type="radio" name="test" value="one" id="one">one
<input type="radio" name="test" value="two" id="two">two
<button id="click">Click</button>

和我的JS

$("#click").click(function(){
  if($('input[type="radio"]').attr('id') == 'one'){
    alert ("one")
  } else{
    alert("two")
  }
})

我的问题是为什么警报二不显示? 有什么身体帮助吗? 谢谢你http://jsfiddle.net/dedi_wibisono17/gydrw291/10/

请参阅.attr的文档

.attr()方法仅获取匹配集中第一个元素的属性值。 要单独获取每个元素的值,请使用循环构造...

因为您的选择器

input[type="radio"]

将始终返回在前面包含#one元素的集合,您的if语句将始终求值为true

为了解决这个问题,有你的选择字符串只选择选中后的单选按钮-所以,使用:checked伪选择器以及:

 $("#click").click(function() { if ($('input[type="radio"]:checked').attr('id') == 'one') { alert("one") } else { alert("two") } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" name="test" value="one" id="one">one <input type="radio" name="test" value="two" id="two">two <button id="click">Click</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM