有没有办法在 "click" 或 "change" 事件处理程序中获取以前的无线电值?

Is there a way to get previous radio value in "click" or "change" event handler?

我需要知道用户是点击了已经选中的收音机还是做了新的选择。 现在我通过 "focus"、"click" 和 "change" 事件组合检测到它(将旧值存储在 "focus" 中,并将其与 "click" 或 [=26 中的当前值进行比较=] 来检测和处理对已检查收音机的点击)。

澄清一下:我无法在点击处理程序中存储之前的状态,因为我无法在此处获取初始状态;或 "focus+click" 或 "load+(prev)click+click";

但这对我来说似乎是个 hack,我认为有 更直接的方法 使用内置 jquery 功能来做到这一点,仅使用一个事件处理程序。 有这样的吗?

提前致谢!

按照@Bukent Vural 的建议使用mousedown

获取$('input[name=test]:checked').val();更改前的当前值, 其中 'test' 是您的无线电输入的名称。

看看这个JSFiddle.

编辑

如果您还想检测标签点击,则需要添加第二个事件处理程序:

$('label').click(function() {
       labelID = $(this).attr('for');
       $('#'+labelID).trigger('mousedown');
});

查看更新后的JSFiddle.

您还可以在数据属性中保留选中值的副本,然后在点击处理程序中进行相应更新:

$('input[name=test]').click(function(){
    var previous = $('input[name=test][data-checked=true]')[0];
    console.log(`previous: ${previous.id}`);
    console.log(`this: ${this.id}`);
    
    // the button was already checked so nothing needs to happen
    if (this.id === previous.id) {
      return;
    }
    
    // update data-checked: add attribute to the current button, remove for the rest
    $(this).attr('data-checked', 'true');
    $('input[name=test]:not(:checked)').removeAttr('data-checked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test1" type='radio' name='test' value='First' checked data-checked='true'>
<label for="test1">First</label><br>

<input id='test2' type='radio' name='test' value='Second'>
<label for="test2">Second</label><br>

<input id='test3' type='radio' name='test' value='Third'>
<label for="test3">Third</label><br>