jQuery 使用 "this" onblur 后对焦

jQuery focus after onblur using "this"

我有几个字段需要在 onblur 之后检查最小值,如果值不正确,则 return 到字段。 $(this).focus() 似乎不起作用。

$(".PartMin").blur(function()
{
    var Value = this.value.replace("$", "");
    if(Value < 115)
    {
        alert("Value cannot be less than 5.00");
        $(this).focus();
    }
});

在模糊回调中设置焦点通常是有问题的。我发现引入延迟有帮助:

$(".PartMin").blur(function()
{
    var Value = this.value.replace("$", "");
    if(Value < 115)
    {
        alert("Value cannot be less than 5.00");
        var element = this;
        setTimeout(function() {
          $(element).focus();
        }, 50);
    }
});

Live Example(由于代码段 UI 而不适用于 Stack Snippets)。


但是:我强烈建议不要对模糊进行侵入式验证(弹出警报)。让用户在字段中移动,并提供非侵入式反馈(颜色等),并且仅在他们尝试使用数据确认操作时提供侵入式反馈。