简体   繁体   English

为什么这个jQuery事件会运行两次?

[英]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. 当您运行此代码并单击input2 ,它将获得焦点,而.result div将输出"f2"一次。 But when you click input1 , the script will let input2 get the focus and .result div will output "f2" twice, why? 但是当你点击input1 ,脚本会让input2获得焦点,而.result div会输出"f2"两次,为什么?

<!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 : 这是一个已知的jquery错误:

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

IE incorrectly calls the focus twice. IE错误地将focus调用两次。

Update: Fixed... switched to focusin from focus removing the not getting focus in input2 bug. 更新:修复...从焦点切换到focusin删除input2 bug中没有获得焦点。

This appears to be an Internet Explorer only issue. 这似乎只是Internet Explorer的问题。 Add a call to preventDefault to fix the double focus issue. 添加一个对preventDefault的调用来修复双焦点问题。 Here's a jsFiddle of it working for me . 这是一个适合我的jsFiddle

<!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. 当您最终绑定focus()事件两次时,可能会发生这种情况。 It may be worth exploring this, and clearing existing bindings before the code. 可能值得探讨这一点,并在代码之前清除现有绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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