Jquery取消选中单选按钮不起作用

Lee*_*Lee 0 javascript jquery

这应该是正确的代码,但它不起作用

<input type="radio" name="test">1
<input type="radio" name="test">2

$('input[name=test]').click(function() { 
    $('input[name=test]').attr(‘checked’,false);
});
Run Code Online (Sandbox Code Playgroud)

这里的例子

http://jsfiddle.net/8jKJc/16/

编辑:

我忘了应该说的话,如果检查然后取消选中它

Jam*_*ice 5

更改.attr.prop,它会正常工作.您还需要将"正在检查"周围使用的引号更改为正确的类型,因为这也会导致它在此时中断:

$('input[name=test]').click(function() { 
    $(this).prop('checked',false);
});
Run Code Online (Sandbox Code Playgroud)

你可以在这个例子中看到这个小提琴.

更新(根据评论)

现在我实际上了解了所需要的东西,需要采用不同的方法.您需要checked通过将属性存储在属性中来记住该属性的先前值:

$('input[name=test]').click(function(e) { 
    var previous = $(this).attr('previous');
    if(previous){
        $(this).prop('checked', false)
    }
    $(this).attr('previous', $(this).prop('checked'));
});
Run Code Online (Sandbox Code Playgroud)

看到这个工作在这里.

更新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'));
});
Run Code Online (Sandbox Code Playgroud)