簡體   English   中英

為什么這個jQuery事件會運行兩次?

[英]Why does this jQuery event run twice?

當您運行此代碼並單擊input2 ,它將獲得焦點,而.result div將輸出"f2"一次。 但是當你點擊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>

這是一個已知的jquery錯誤:

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

IE錯誤地將focus調用兩次。

更新:修復...從焦點切換到focusin刪除input2 bug中沒有獲得焦點。

這似乎只是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()事件兩次時,可能會發生這種情況。 可能值得探討這一點,並在代碼之前清除現有綁定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM