焦点/模糊上的Firefox错误的解决方法

问题描述

我编写了以下代码来检查输入字段中插入的值在数据库中是否已经存在。

$('#nome_field').blur(function(){
        var field_name=$('#nome_field').val();
        $.ajax({
          url: "check_field_unique.PHP",method: 'post',data: {field_name:field_name},dataType: "json"
        }).done(function(data){
            if(data.status==500){
              //esiste un altro campo con lo stesso nome
              bootBox.alert({
                message: data.message,size: 'small',backdrop: true,callback: function(){
                    //$('#nome_field').val('');
                    $('#nome_field').focus();           
                }
              });
            }       
        });
    });

它在除Firefox之外的所有浏览器中都能正常运行。有a known bug opened 20(!!) years ago仍会影响Firefox,导致焦点和模糊之间无限循环。 当代码到达$('#nome_field').focus();行时,它将聚焦,然后再次触发模糊并再次运行验证(无限循环)。

如果我将此行$('#nome_field').val('');分解,则$('#nome_field').focus();将永远不会执行,但输入将被清除。我的期望是,通过清除输入字段,我可以修复该错误。无论如何,所需的行为是保留用户编写的内容以供他修复,而不是清除输入。

有人知道如何解决此问题吗?

解决方法

一种解决方法是,您可以对安全检查进行编码,以确保在设置焦点后不会立即发生模糊。

$('#nome_field').blur(function() {
  var tb = $(this);
  if (tb.data("ignore")) {
    return;
  }
  var field_name = tb.val();
  $.ajax({
    url: "check_field_unique.php",method: 'post',data: {
      field_name: field_name
    },dataType: "json"
  }).done(function(data) {
    if (data.status == 500) {
      //esiste un altro campo con lo stesso nome
      bootbox.alert({
        message: data.message,size: 'small',backdrop: true,callback: function() {
          //$('#nome_field').val('');
          tb.data("ignore",true)
          tb.focus();
          window.setTimeout(function () {
            tb.removeData("ignore");
          },100);
        }
      });
    }
  });
});