2016-02-14 111 views
4

在下面的代碼,爲什麼事後被解僱三次? 「文字標記!」在輸入框後面追加三次。jQuery的觸發的事件多次

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $("input").select(function(){ 
     $("input").after(" Text marked!"); 
    }); 
    $("button").click(function(){ 
     $("input").trigger("select"); 
    }); 
}); 
</script> 
</head> 
<body> 

<input type="text" value="Hello World"><br><br> 

<button>Trigger the select event for the input field</button> 

</body> 
</html> 
+0

因爲你點擊該按鈕3次?我直接將代碼複製到jsfiddle中並且工作正常。 – mmaceachran

+0

@mmaceachran無法在Chrome中,它不:https://jsfiddle.net/rmns4pyq/1/ – BenM

+0

FWIW,這似乎是在瀏覽器的錯誤。嘗試在Firefox中,它運行良好。 – BenM

回答

5

我可以確認這發生在我身上的鉻。我真的不知道爲什麼,但你可以通過添加event.preventDefault()來修復它。

$("input").select(function(event){ 
    event.preventDefault(); 
    $("input").after(" Text marked!"); 
}); 

演示:http://jsbin.com/yedoxov/edit?html,js,output