使用JQuery,为单选按钮设置onclick事件侦听器的最佳方法是什么?

Jay*_*ett 10 javascript jquery

对于以下HTML:

<form name="myForm">
    <label>One<input  name="area"  type="radio" value="S"  /></label>
    <label>Two<input name="area"   type="radio" value="R" /></label>
    <label>Three<input name="area"   type="radio" value="O" /></label>
    <label>Four<input name="area" type="radio" value="U" /></label>
</form>
Run Code Online (Sandbox Code Playgroud)

从以下javascript代码更改:

$(function() {
     var myForm = document.myForm;
     var radios = myForm.area;

     // Loop through radio buttons
     for (var i=0; i<radios.length; i++) {
        if (radios[i].value == "S") {
            radios[i].checked = true;   // Selected when form displays
            radioClicks();   // Execute the function, initial setup
        }
        radios[i].onclick = radioClicks;  // Assign to run when clicked
     }  
 });
Run Code Online (Sandbox Code Playgroud)

谢谢

编辑:我选择的响应回答了我问的问题,但是我喜欢使用bind()的答案,因为它还显示了如何区分单选按钮组

rp.*_*rp. 19

$(document).ready(function(){
    $("input[name='area']").bind("click", radioClicks);
});

functionradioClicks() {
    alert($(this).val());
}
Run Code Online (Sandbox Code Playgroud)

我喜欢使用bind()而不是直接连接事件处理程序,因为你可以将其他数据传递给事件处理程序(此处未显示,但数据是第三个bind()参数)并且因为您可以轻松解除绑定(并且您可以绑定和取消绑定按组 - 参见JQuery文档).

http://docs.jquery.com/Events/bind#typedatafn


Jua*_*uan 18

$( function() {
    $("input:radio")
        .click(radioClicks)
        .filter("[value='S']")
        .attr("checked", "checked");
});
Run Code Online (Sandbox Code Playgroud)