Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Keyup event behavior on tab

HTML:

<form id="myform">
    <input id="firstfield" name="firstfield" value="100" type="text" />
    <input id="secondfield" name="secondfield" value="200" type="text" />
</form>

jQuery:

jQuery(document).ready(function() {
    $('#firstfield').keyup(function() {
      alert('Handler for firstfield .keyup() called.');
    });
    $('#secondfield').keyup(function() {
      alert('Handler for secondfield .keyup() called.');
    });
});

Demo: http://jsfiddle.net/KtSja/3/

In this demo, if you place your cursor in the first field and then tab out (without making any changes), the keyup event is fired on the second field. i.e., you are tabbing out of first field and into second field. Is this behavior correct? How can I prevent this from happening? Same applies to shift + tab.

Note:

a) I believe all other keys, printable and non-printable, trigger the keyup event on the first field.

b) The event isn't triggered at all if you keep the tab pressed until it moves out of both fields.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A key's default action is performed during the keydown event, so, naturally, by the time keyup propagates, the Tab key has changed the focus to the next field.

You can use:

jQuery(document).ready(function() {
    $('#firstfield, #secondfield').on({
        "keydown": function(e) {
            if (e.which == 9) {
                alert("TAB key for " + $(this).attr("id") + " .keydown() called.");
            }
        },
        "keyup": function(e) {
            if (e.which != 9) {
                alert("Handler for " + $(this).attr("id") + " .keyup() called.");
            }
        }
    });
});

This way, if the Tab key is pressed, you can make any necessary adjustments before handling other keys. See your updated fiddle for an exampe.

Edit

Based on your comment, I revamped the function. The JavaScript ended up being a bit complicated, but I'll do my best to explain. Follow along with the new demo here.

jQuery(document).ready(function() {
    (function($) {
        $.fn.keyAction = function(theKey) {
            return this.each(function() {
                if ($(this).hasClass("captureKeys")) {
                    alert("Handler for " + $(this).attr("id") + " .keyup() called with key "+ theKey + ".");
                    // KeyCode dependent statements go here.
                }
            });
        };
    })(jQuery);

    $(".captureKeys").on("keydown", function(e) {
        $("*").removeClass("focus");
        $(this).addClass("focus");
    });
    $("body").on("keyup", "*:focus", function(e) {
        if (e.which == 9) {
            $(".focus.captureKeys").keyAction(e.which);
            $("*").removeClass("focus");
        }
        else {
            $(this).keyAction(e.which);
        }
    });
});

Basically, you give class="captureKeys" to any elements on which you want to monitor keypresses. Look at that second function first: When keydown is fired on one of your captureKeys elements, it's given a dummy class called focus. This is just to keep track of the most recent element to have the focus (I've given .focus a background in the demo as a visual aid). So, no matter what key is pressed, the current element it's pressed over is given the .focus class, as long as it also has .captureKeys.

Next, when keyup is fired anywhere (not just on .captureKeys elements), the function checks to see if it was a tab. If it was, then the focus has already moved on, and the custom .keyAction() function is called on whichever element was the last one to have focus (.focus). If it wasn't a tab, then .keyAction() is called on the current element (but, again, only if it has .captureKeys).

This should achieve the effect you want. You can use the variable theKey in the keyAction() function to keep track of which key was pressed, and act accordingly.

One main caveat to this: if a .captureKeys element is the last element in the DOM, pressing Tab will remove the focus from the document in most browsers, and the keyup event will never fire. This is why I added the dummy link at the bottom of the demo.

This provides a basic framework, so it's up to you to modify it to suit your needs. Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...