这应该是正确的代码,但它不起作用
<input type="radio" name="test">1
<input type="radio" name="test">2
$('input[name=test]').click(function() {
$('input[name=test]').attr(‘checked’,false);
});
这里是例子
编辑:
我忘记了应该说如果已选中然后取消选中的行
最佳答案
将.attr
更改为.prop
,它将正常工作。您还需要将“checked”周围使用的引号更改为正确的类型,因为这也会导致它此刻中断:
$('input[name=test]').click(function() {
$(this).prop('checked',false);
});
您可以在 example fiddle 中看到它的工作原理.
更新(基于评论)
既然我真正了解了需要什么,就需要一种不同的方法。您需要通过将其存储在属性中来记住 checked
属性的先前值:
$('input[name=test]').click(function(e) {
var previous = $(this).attr('previous');
if(previous){
$(this).prop('checked', false)
}
$(this).attr('previous', $(this).prop('checked'));
});
查看此工作 here .
更新 2(基于进一步的评论)
第一次更新中的上述代码不太有效,因为当单击集合中的不同单选按钮时,先前检查的单选按钮的 previous
属性仍保持设置,但单选按钮实际上并未设置检查过。我们可以通过以下方式避免这种情况:
var previousElem;
$('input[name=test]').click(function(e) {
var previous = $(this).attr('previous');
if(previous && previousElem === this){
$(this).prop('checked', false);
}
previousElem = this;
$(this).attr('previous', $(this).prop('checked'));
});
关于javascript - Jquery 取消选中单选按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6467598/