Ala*_*blo 0 checkbox jquery radio-button
我想使用复选框模拟单选按钮行为,这表示:
选中复选框后,将取消选中所有其他具有相同名称的复选框(此处为选择器)
但是,如果我尝试做类似的事情:
$('body').delegate('.myradio', 'click', function(e) {
$('.myradio').prop('checked', false);
$(this).prop('checked', true);
});
Run Code Online (Sandbox Code Playgroud)
这会触发change事件两次.
如果我尝试添加e.preventDefault:
$('body').delegate('.myradio', 'click', function(e) {
$('.myradio').prop('checked', false);
$(this).prop('checked', true);
e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
根本不会触发任何事件,也不会选中该复选框.
最后,如果我尝试自己触发事件:
$('body').delegate('.myradio', 'click', function(e) {
$('.myradio').prop('checked', false);
$(this).prop('checked', true);
e.preventDefault();
$(this).change();
});
Run Code Online (Sandbox Code Playgroud)
该change事件也被调用两次.
有关信息,我的所有复选框都有唯一的ID.
除了选中的复选框之外,禁用所有复选框的方法是什么?
如果我正确理解你的问题,以下应该有效.
$('body').delegate('.myradio', 'click', function (e) {
var $element = $(this)[0];
$('.myradio').each(function () {
if ($(this)[0] !== $element)
$(this).prop('checked', false);
});
});
Run Code Online (Sandbox Code Playgroud)
这样,复选框组的行为类似于单选按钮组.除非您可以取消选择所选项目.
$('body').delegate('.myradio', 'click', function (e) {
var $element = $(this)[0];
if ($(this).prop('checked') == false) {
$(this).prop('checked', true);
return;
}
$('.myradio').each(function () {
if ($(this)[0] !== $element)
$(this).prop('checked', false);
});
});
Run Code Online (Sandbox Code Playgroud)