Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - .focus() "set focus on a target input" will not work in Firefox

I have an input field. Under certain conditions I want to keep the user focused on the input field when they hit the Tab key. Basically I'm mimicking the functionality of Google's auto populating search box. I have everything working fine in every browser except the one I never have problems with... Firefox!?

The following code works as expected in IE, Chrome and Safari, if you Tab out of the textbox with class myInput, your focus stays in the textbox. But in Firefox, when you Tab out of the textbox, you will go to the next textbox. (This is a very simplified version of what I am doing. If I can get this to work, I'll be able to get my real code to work.)

$(document).ready(
    function()
    {               
        $(".myInput").blur
        (
            function()
            {
                $(this).focus();
                $(this).select();
            }
        );      
    }
);

PS. Please don't suggest a fix using setTimeout(). Thanks.

I have read articles describing how jQuery has .focus() and javascript has .focus() and how they are not the same. I understand this (I think), but I still am not able to figure out what I am doing wrong.

ADDED... I can get it to work this way

$(document).ready(
    function()
    {               
        $(".myInput").blur
        (
            function()
            {
                setTimeout("$('.myInput').focus();",1);
            }
        );      
    }
);

Seems hackish but I can't figure out why Firefox won't set focus on blur. So, if any of you have the answer, it would be nice to know.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you are using jQuery should use the .focusout() method.

http://api.jquery.com/focusout/

This is distinct from the blur event in that it supports detecting the loss of focus from parent elements (in other words, it supports event bubbling).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...