jQuery和单选按钮组
在jQuery中,我想选择所有没有选中按钮的单选按钮组。
或者,有没有一种方法可以选择所有单选按钮组并遍历组?
我正在动态地向页面添加N个单选按钮组,并且不会事先知道单选按钮组的名称。
要查找所有广播组:
var radio_groups = {} $(":radio").each(function(){ radio_groups[this.name] = true; })
找到哪个无线电组已检查无线电盒,哪些没有:
for(group in radio_groups){ if_checked = !!$(":radio[name='"+group+"']:checked").length alert(group+(if_checked?' has checked radios':' does not have checked radios')) }
支持多个组并预先检查。
$('input').click(function() { var $t = $(event.target); if ($t.hasClass('checked')) $t.removeAttr('checked'); else $('input[type="radio"][name="' + $t.prop('name') + '"]').not($t).removeClass('checked'); $t.toggleClass('checked'); }).filter(':checked').addClass('checked');
“`
certificate: http : //jsfiddle.net/abrkn/PGW2Z/
要按组名选择所有无线电,只获取不同名称的列表:
function selectRadioByGroupName() { return $.unique($('input:radio').map(function(index, element) { return this.name; })); }
一个示例代码段:
function selectRadioByGroupName() { return $.unique($('input:radio').map(function(index, element) { return this.name; })); } $(function () { selectRadioByGroupName().each(function(index, element) { $('body').append($('First Group name is: ' + element + '
')); }); });