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

Why does this jQuery event run twice?

本文关键字:两次 运行 jQuery 事件 为什么      更新时间:2023-09-26

当您运行此代码并单击input2时,它将获得焦点,.resultdiv将输出"f2"一次。但是当您单击input1时,脚本将让input2获得焦点,.resultdiv将输出"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>

这是一个已知的jquery bug:

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

IE错误调用focus两次

更新:修复…从focus切换到focusin,删除了input2中无法获得focus的错误。

这似乎是Internet Explorer独有的问题。添加一个对preventDefault的调用来修复双焦点问题。这是一个为我工作的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> 

虽然它似乎不被复制,但我已经看到当多个事件绑定到控件时发生这种问题。当您绑定了focus()事件两次时,就会发生这种情况。这可能值得探索,并在代码之前清除现有的绑定。