繁体   English   中英

jQuery如何使用单选按钮来控制单选按钮

[英]jQuery How to Use radio button to control radio buttons

 $(function() { $("#aa").click(function() { $("#aa2").attr("checked", true); }); $("#bb").click(function() { $("#bb2").attr("checked", true); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='radio' name='a' id='aa'/>aa <input type='radio' name='a' id='bb'/>bb <br> <input type='radio' name='b' id='aa2'/>aa2 <input type='radio' name='b' id='bb2/'>bb2 

当我单击aa,aa2选中时,单击bb,bb2 2了一下。 但是,然后单击aa,bb2保持选中状态,而aa2未被选中

您可能需要使用.prop()方法而不是.attr()方法。

使用.attr() ,要设置一个属性。 设置属性后,将设置属性。 在您的情况下,如果已经设置了属性,则不会再次更改该属性,因此,您应该仅使用.prop()来更改该属性。

附带说明,我建议您收听单选元素的change事件,而不是click事件。

这里的例子

$("#aa").on('change', function () {
    $("#aa2").prop("checked", "checked");
});
$("#bb").on('change', function () {
    $("#bb2").prop("checked", "checked");
});

参见.prop().attr()

这应该为你工作

 $(function() { $("input[name=a]").change(function() { $("input[name=b]").removeAttr('checked'); $("input[name=b]").filter('[value='+$(this).val()+']').attr('checked', true); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='radio' name='a' value="1" />aa <input type='radio' name='a' value="2" />bb <br> <input type='radio' name='b' value="1" />aa2 <input type='radio' name='b' value="2" />bb2 

暂无
暂无

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

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