Focus selector not work

北城以北 提交于 2020-01-06 18:08:31

问题


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>

来源:https://stackoverflow.com/questions/16956906/focus-selector-not-work

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