简体   繁体   中英

Why does this jQuery event run twice?

When you run this code and click input2 , it will get the focus and .result div will output "f2" once. But when you click input1 , the script will let input2 get the focus and .result div will output "f2" twice, why?

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>blank</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){   
    $(".input1").click(function(){$(".input2").focus();});
    $(".input2").focus(function(){$(".result").html($(".result").html()+"f2, ");});
});
</script>
</head>

<body>
    <p>
        <input class="input1" value="click me to set the input2's focus" />
        <input class="input2" value="input2" />
        <div class="result"></div>
    </p>
</body>
</html>

This is a known jquery bug :

http://bugs.jquery.com/ticket/6705

IE incorrectly calls the focus twice.

Update: Fixed... switched to focusin from focus removing the not getting focus in input2 bug.

This appears to be an Internet Explorer only issue. Add a call to preventDefault to fix the double focus issue. Here's a jsFiddle of it working for me .

<!DOCTYPE html> 
<html> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>blank</title> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
      $(document).ready(function(){ 
      $(".input1").click(function(){$(".input2").focus();}); 
      $(".input2").focusin(function(e)
      {
        e.preventDefault();
        $(".result").html($(".result").html()+"f2, ");
      }); 
    </script> 
  </head> 

  <body> 
    <p> 
      <input class="input1" value="click me to set the input2's focus" /> 
      <input class="input2" value="input2" /> 
      <div class="result"></div> 
    </p> 
  </body> 
</html> 

Although it appears not to be replicated, I have seen this sort of problem occur when multiple events are bound to the control. This can occur when you end up binding the focus() event twice. It may be worth exploring this, and clearing existing bindings before the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM