如何在自定义 jQuery return false 时防止单选按钮松动 "focus"?

How to prevent radiobutton loose "focus" when custom jQuery return false?

我有 3 个同名的单选按钮 (属性)。 如果选中“已删除”单选按钮并且有人会单击“活动”,我希望 运行 自定义函数 return 是真还是假。如果它失败了,我想防止“已删除”收音机被取消选中。

问题是单选按钮失去了“焦点”并且选择了“活动”单选按钮。

我已经使用下面的代码来防止这种情况,但它似乎是一种肮脏的解决方法。

如果自定义函数 return false,是否有更好的方法来防止取消选中“已删除”单选按钮?

$("#radioActive").on("change", function() {
  if (!CustomFunction1()) {
    $("#radioUnactive").prop('checked', true);
    bootbox.alert('No Pain No Game');
  }
});

$("#radioUnactive").on("change", function() {
  if ($('#distributor').val() == '1') {
    $("#radioActive").prop('checked', true);
    bootbox.alert('NO NO NO')
  }
  if (CustomFunction2()) {
    $("#radioActive").prop('checked', true);
    bootbox.alert('Distributor has assigned users - cannot be disabled ');
  }
});

$("#radioDelete").on("change", function() {
  if ($('#distributor').val() == '1') {
    $("#radioActive").prop('checked', true);
    bootbox.alert('NO NO NO!');
  }
  if (CustomFunction2()) {
    $("#radioActive").prop('checked', true);
    bootbox.alert('No Way')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.5.2/bootbox.min.js" integrity="sha512-RdSPYh1WA6BF0RhpisYJVYkOyTzK4HwofJ3Q7ivt/jkpW6Vc8AurL1R+4AUcvn9IwEKAPm/fk7qFZW3OuiUDeg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div class="radio-toolbar">
  <input type="radio" id="radioActive" name="Buttons[activeState]" value="active">
  <label for="radioActive">Active</label>

  <input type="radio" id="radioUnactive" name="Buttons[activeState]" value="unactive">
  <label for="radioUnactive">Unactive</label>

  <input type="radio" id="radioDelete" name="Buttons[activeState]" value="deleted">
  <label for="radioDelete">Deleted</label>
</div>

与其编写多个代码,不如一次完成。

一个示例是首先保存之前选中的单选按钮 ID,然后根据函数内部的一些检查及其 return 值来选中新的单选按钮或仅选中前一个单选按钮。

var prevCheckedId = '';

$('input[type=radio]').mouseup(function(){
    prevCheckedId = $('input[type=radio]:checked').attr('id');
}).change(function(){
    var value = $(this).val();
    if(CustomFunction1(value)) {
      $(this).prop('checked', true);
    }else{
      $(this).prop('checked', false);
      $('#'+prevCheckedId).prop('checked', true);
    }
});

function CustomFunction1(value){
  if(value == 'active'){
    return false;
  }else{
    return true;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar">
    <input type="radio" id="radioActive" name="Buttons[activeState]" value="active">
    <label for="radioActive">Active</label>

    <input type="radio" id="radioUnactive" name="Buttons[activeState]" value="unactive">
    <label for="radioUnactive">Unactive</label>

    <input type="radio" id="radioDelete" name="Buttons[activeState]" value="deleted">
    <label for="radioDelete">Deleted</label> 
</div>