[英]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.