Issues with using onBlur event

我是研究僧i 提交于 2019-12-06 11:08:59

After reviewing your code, best I can tell you are experiencing an unusual bug in jQuery. I have seen some quirky things happen when using focus() (like having to use setTimeout). But, in your case the $(this) is somehow not resolving correctly when calling focus().

At first I thought it was because the id is not following HTML-4 standards, but correcting the id did not help. $(this) still failed to focus, despite the fact it correctly refers to the <input> element. Then I tried identifying the id with jQuery as a string $("'#" + thisId + "'")...still did not work. But, a hard coded id did work...

So, here's how I modified your code and worked around the problem to get it to focus

if( null === $text.match(/\b(1Z ?[0-9A-Z]{3} ?[0-9A-Z]{3} ?[0-9A-Z]{2} ?[0-9A-Z]{4} ?[0-9A-Z]{3} ?[0-9A-Z]|[\dT]\d\d\d ?\d\d\d\d ?\d\d\d)\b/))
{
    alert("No Match");    
    //$(this).focus();//don't use jquery $this
    var thisId = $(this).attr('id');//get the id
    //use the setTimeout workaround for firefox
    setTimeout(function() {
      document.getElementById(thisId).focus();//use javascript to set focus
    },0);
    $(this).css('background-color','Red');
}

Feel free to look at the fiddle (linked above). This approach does correct the focus problem.

I figured out the issue. It turns out that IE and FireFox have very different behavior when it comes to onBlur.

I was calling focus() during the execution of the blur(). since the blur has not completed it either ignored the focus command or executes and then completes the blur.

Some browsers the focus command can cause a blur to be triggered thus creating an infinite loop with the cursor bouncing between the two fields.

Using a timeout will cause the focus to trigger outside of the blur call back function.

Under IE I can make use of onBlur and have no issues, under FF the focus never got called event with a timeout, so it needs an onChange.

I have updated my script - it runs fine on IE - http://jsfiddle.net/boyd4715/3wbtQ/34/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!