0

I have the following code to check if the users' text does not contain the two forbidden characters and it does go the way I want. the problem is that for the texts containing the forbidden characters, I want to focus on the input after the alert goes off. yet the css style is applied to the input.

What point am I missing in this piece of code?

$(".option, .fixed").blur(function(){
    var str = $(this).val();
    if(str.indexOf("|") >= 0 || str.indexOf(":") >= 0) {
        alert("The informatin you provided contains illegal characters( | : )");    
    }
    $(this).css('border','1px solid pink').focus();
});
4

2 回答 2

1

当事件在 DOM 树中冒泡时,您的代码会blur在它完全解决之前执行。只有当事件到达堆栈底部并由浏览器处理时,元素才会失去焦点。

如果您.focus()在该函数内部调用,则该focus动作将被执行,然后该blur动作将被恢复,并且原始输入最终将失去其焦点。

您需要在浏览器处理完focus 之后触发。blur

您可以使用setTimeout

$(".option, .fixed").blur(function(){
    var str = $(this).val();
    if(str.indexOf("|") >= 0 || str.indexOf(":") >= 0) {
        alert("The informatin you provided contains illegal characters( | : )");    
    }
    $(this).css('border','1px solid pink');

    var that = this;
    setTimeout( function(){ $(that).focus() }, 0 );
});

但是,您应该意识到与此模式相关的问题:给focus一个节点可能会触发blur另一个节点,并导致奇怪/损坏的 gui 行为。

这是一个示例(此处为jsfiddle):

  • 单击第一个输入,然后单击它之外:您将看到所需的行为,
  • 单击第一个输入,然后单击第二个:您将有一个无限blur/focus循环和一个不可用的 gui。

避免这种情况的最简单方法是突出显示该字段,显示错误消息,然后让焦点成为焦点。

于 2013-05-29T07:01:33.880 回答
0

对适合我的情况的 LeGEC 解决方案稍作改动:

$(".option, .fixed").blur(function(){
    var str = $(this).val();
    if(str.indexOf("|") >= 0 || str.indexOf(":") >= 0) {
        alert("The informatin you provided contains illegal characters( | : )");
        $(this).css('border','1px solid pink');
        var that = this;
        setTimeout( function(){ that.focus() }, 0 );
    }else{
        $(this).css('border','1px solid #ccc');
    }
});
于 2013-05-29T08:01:23.630 回答