2016-02-14 115 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