$(document).ready(function(){
$("input").select(function(){
$("input").after(" Text marked!");
});
$("button").click(function(){
$("input").trigger("select");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<input type="text" value="Hello World"><br><br>
<button>Trigger the select event for the input field</button>
有人能告诉我为什么点击按钮后 select 事件会触发 3 次吗?
似乎使用IE和Chrome会导致不同的结果。
最佳答案
JQuery - Why does Trigger method call it three times?
似乎在 button
的 click
事件中被调用了两次;在
$("input").trigger("select");
select
事件的默认处理程序
$("input").select(function(){
$("input").after(" Text marked!");
});
要在 button
的 click
或 input
字段中的用户选择时调用一次,请尝试检查 event.isTrigger
确定 event
是否被 .trigger()
$(document).ready(function(){
$("input").select(function(e){
if (!e.isTrigger)
$("input").after(" Text marked!");
});
$("button").click(function(){
$("input").trigger("select");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input />
<button>click</button>
或者,使用 setTimeout
允许在 .trigger("select")
称为 ;在 button
元素的 click
$(document).ready(function() {
$("input").select(function(e) {
console.log(e);
$("input").after(" Text marked!")
})
$("button").click(function() {
setTimeout(function() {
$("input").trigger("select");
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input />
<button>click</button>
关于javascript - JQuery - 为什么 Trigger 方法调用它三次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907765/