开发者

Help with focus/blur semantics in jquery

...

  $(document).ready(function(){

        $('form').submit(function(){
                $('input#second').focus();
                return false;
        });

        $('#first').blur(function(){
                alert('blur');
        });
  });

...

  <form>
    <input id=first><br>开发者_如何学C;
    <input id=second><br>
    <input type=submit>
  </form>

...
  1. Load the page
  2. Click on first input to give it focus
  3. Hit Enter to submit the form

Then the following happens:

  1. $('form').submit() is called and
  2. It sets focus to the #second input and exits
  3. #first looses focus, #second gets it, but...
  4. $('#first').blur() is not called

Here is a live demo.

What am I missing?

Thanks


Nick is right your HTML is really messed up. You have not ended you input tags or the br(s). On top of that you should put your attribute values in your input tags in double quotes.

This works here is a demo http://www.jsfiddle.net/dAdG8/

<script type="text/javascript">
$(document).ready(function(){
    $('form').submit(function(){
         $('input#second').focus();
         return false;
    });

     $('#first').blur(function(){
         alert('blur');
     });

     // logging
     $('input').blur(function(){
         $('pre').append('blur, ' + this.id + '\n');
     });

     $('input').focus(function(){
         $('pre').append('focus, ' + this.id + '\n');
     });
});
</script>

<form>
     <input id="first" />
     <br />
     <input id="second" />
     <br />
     <input type="submit" />
 </form>


According to this comment over at JQuert bugtracker, the work around the problem is to use

$('input#second')[0].focus();

instead of

$('input#second').focus();

Whether it is a bug is still to be decided by jq people in charge, but I would guess that it is because

  1. the behaviour appears to be browser-specific
  2. no reason why calling focus() on the array with one element should not be the same as calling it specifically for that element

Thanks, everyone. Night.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜