切换两个隐藏单选按钮的最佳方式是什么

What is the best way to toggle two hidden radio buttons?

本文关键字:单选按钮 最佳 方式 是什么 隐藏 两个      更新时间:2024-05-04

我有两个隐藏的单选按钮和一个可见按钮。单击此按钮应切换选中的按钮。

我可以使用if语句实现这一点,只需设置单选按钮(ID)=选中即可。

但是,如何用最少的代码来实现这一点呢?

更新
为了满足那些除了抱怨代码缺失之外别无选择的人。尽管如此,我不认为这会使问题变得更加constructive

<div class="switch">
    <input id="check1" type="radio" name="search" class="rbtn-search" checked="checked" value="brand" />
    <input id="check2" type="radio" name="search" class="rbtn-search" checked="" value="store" />
</div>

$('.switch').click(function(){
  // Switch the radio buttons here
})

参见演示

HTML

<div id="container">
  ​<input type="radio" checked="checked">
  <input type="radio">
  <a class="button" href="#">button</a>
</div>

JavaScript

$('#container .button').click(function () {
    $('#container :radio').each(function () {
      $(this).attr('checked', !$(this).attr('checked'));
    });
});​

您可以使用映射:

 <input type="radio" checked="checked">
 <input type="radio">
 <a id="btn">I'm a bbutton</a>​

jQuery("#btn").click(function() {
    jQuery(":radio").map(function() { this.checked = !this.checked; });        
});​

Fiddle

$("#toggle").click(function(){
    $(':radio').each(function(){
        $(this).attr('checked', !$(this).attr('checked'));
    })
});

您可以尝试;

$('#button').click(function () {
    $(':radio').each(function () {
        $(this).attr('checked', !$(':radio').attr('checked'));
    });
});

这是正在工作的小提琴

或者通过这种方式使用class;

$('#button').click(function () {
    $('.radiobtn').each(function () {
        $(this).attr('checked', !$('.radiobtn').attr('checked'));
    });
});

这是正在工作的fidd