單選框需要在使用者選擇時立刻有反應,最直白的做法就是幫它綁 click 事件,並在回呼裡透過 $(this).val() 取出被選項的值。
<html>
<head>
<title>單選框 radio 綁定 click 事件</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(function(){
$(":radio").click(function(){
alert("您是..." + $(this).val());
});
});
</script>
<style type="text/css">
h5{color:blue;}
textarea{resize:none;}
#word{color:red;}
</style>
</head>
<body>
<h5>單選框 radio 綁定 click 事件</h5>
<form action="" method="">
<input type="radio" name="gender" value="男性">男性
<input type="radio" name="gender" value="女性">女性
<input type="radio" name="gender" value="其他">其他
</form>
</body>
</html>
$(":radio") 會選出頁面上所有 type 為 radio 的 input。若頁面有多組單選框,建議改用 $("input[name='gender']") 限定範圍,避免誤觸。
因為 name 相同的 radio 是互斥的,點選新選項時只有「被點的那一個」會觸發 click,不會有重複執行的問題。
這裡用 click 沒問題,但更嚴謹的做法是綁 change 事件。差別在於:透過鍵盤方向鍵切換選項時,click 不會觸發而 change 會。若你在意無障礙與鍵盤操作,change 是比較安全的选择。
如果 radio 是透過 Ajax 動態加入的,直接綁定的事件對它們無效。此時改用事件委派:$(document).on("change", "input[type=radio]", function(){...})。