2015-12-01 64 views
-2

我想使我的button元素像单选按钮一样工作。我的意思是,如果我选择一个具有相同名称或ID的人,那么其他人将被取消选择。如何使按钮组具有与一组单选按钮相同的行为

<button name="options" id="options>Button 1</button> 
<button name="options" id="options>Button 2</button> 
<button name="options" id="options>Button 3</button> 

我该怎么做?

+3

'id'应该是同一个文档中是唯一的。 –

+1

你可以使用'class =“options”'而不是 – depperm

+2

你如何实现一个“选定”按钮元素? – Teemu

回答

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>

相关问题