获取单选按钮以前的状态如果以前选中,请单击 event/Uncheck 单选按钮

Get radio button previous state Click event/Uncheck the radio if previously checked

如何查看单选按钮是否已在 click 事件中选中?

实际上我想做的是,如果之前选中了单击的单选按钮,并且用户再次单击同一个单选按钮,则取消选中它。

但是下面的代码总是评估 if 条件 t true :P

$('input.radiooption').click(function(g) {
    if ($(this).is(":checked")) {
        console.log("already checked, now uncheck it");
    } else {
        console.log("Not checked");
    }
});

P.S.

事实是, 当我单击一个未选中的单选按钮时,它被选中

当我点击一个已经选中的按钮时,它会被选中

所以,我想知道一种方法来确定 click 事件中单选按钮的先前状态。

JS FIDDLE

使用临时变量跟踪之前的状态:

var prv;
var markIt = function(e) {
  if (prv === this && this.checked) {
    this.checked = false;
    prv = null; //allow seemless selection for the same radio
  } else {
    prv = this;
  }
};
$(function() {
  $('input.radiooption').on('click', markIt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />

给你:

var makeRadiosDeselectableByName = function(name){
    $('input[name=' + name + ']').click(function() {
        if($(this).attr('previousValue') == 'true'){
            $(this).attr('checked', false)
        } else {
            $('input[name=' + name + ']').attr('previousValue', false);
        }

        $(this).attr('previousValue', $(this).attr('checked'));
    });
};

这里是完整的例子:http://jsfiddle.net/EtNXP/1467/