Focus selector not work

2019-08-21 20:06发布

Go into textfield and input a character. The debugger show you:

$( document.activeElement ) => work, node found + attribute you can read

$(":focus").css("background-color","red") => work

$( ':focus' ) => not work, no node found

Why? Any solutions?

In API doc it's say $( document.activeElement ) is the $( ':focus' ). Only a performance difference.

see: http://api.jquery.com/focus-selector/

Thanks!

<html>
<head>
<title>focus</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"         type="text/javascript"></script>

<script type="text/javascript">

$(function() {

    $(document).keypress(function(event) {

        $(":focus").css("background-color","red"); // <-- work

        var f3    = $( ':focus' ); // <-- NOT work
        var attr3 = f3.attr('tabindex');
        var id3   = f3.attr('id');
        f3.val(id3);

        var f1    = $( document.activeElement ); // <-- work
        var attr1 = f1.attr('tabindex');
        var id1   = f1.attr('id');
        console.log(id1);
        return;
    });
});

</script>
</head>

<body>
  <h1>test focus</h1>

<label>TextBox : </label>
<form>
<input id="textbox1" type="text" size="50" tabindex="1"/><br>
<input id="textbox2" type="text" size="50" tabindex="2"/>
</form>


</body>
</html>

0条回答
登录 后发表回答