如何为按钮组提供与一组单选按钮相同的行为

时间:2015-12-01 17:34:59

标签: javascript jquery

我想让我的<button name="options" id="options>Button 1</button> <button name="options" id="options>Button 2</button> <button name="options" id="options>Button 3</button> 元素像单选按钮一样。我的意思是,如果我选择一个具有相同名称或身份的人,那么其他人将被取消选择。

<table id="myTable">
    <tr><td>apple</td></tr>
    <tr><td>banana</td></tr>
    <tr><td>pear</td></tr>
    <tr><td>watermellon</td></tr>
</table>

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我会将id更改为class,然后您希望充当群组的每组按钮都具有唯一的类名。这是两个按钮组的示例,我添加了通过单击左侧唯一的重新启用按钮的功能

$('button').on('click', function() {
  var name = $(this).attr('name');
  var cl = $(this).attr('class');
  var reenable = false;
  $('.' + cl).each(function() {
    if ($(this).attr('name') != name) {
      if ($(this).attr('disabled') == 'disabled')
        reenable = true;
      else
        $(this).attr('disabled', true);
    }
  });
  if (reenable)
    $('.' + cl).attr('disabled', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button name="options1" class="options">Button 1</button>
<button name="options2" class="options">Button 2</button>
<button name="options3" class="options">Button 3</button>
<br />
<button name="options1" class="options2">Button 1</button>
<button name="options2" class="options2">Button 2</button>
<button name="options3" class="options2">Button 3</button>