嗨,我正在创建 jquery 插件。当我专注于输入框时,我坚持下去,然后它触发了两次。
$(document).ready(function(){
$('#searchText').typefast();
$('#searchText1').typefast();
})
$.fn.typefast=function(){
$('input').focus(function(){
console.log($(this).attr('id'));
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">
`
最佳答案
它运行了两次,因为您在 document.ready
函数中显式调用了 typefast()
两次。即使您的选择器中都缺少 #
,但仍然会在空的 jQuery 包装器上调用 typefast()
。而且,由于 typefast()
实际上并未对其调用的包装集的内容执行任何操作,因此它会继续处理所有 input
元素。因此,最终结果是所有 input
元素都将 typefast
注册到其 focus
事件中两次。
如果(这是一个很大的如果)您要为此使用插件,您应该只调用它一次,因为插件会找到所有输入
元素并设置其事件处理程序。此外,插件具有一定的模式,建议遵循该模式,以确保 $
实际上指向 jQuery 对象并确保方法链接能够正常工作。看起来像这样:
$(function(){
// You would want this to be a jQuery utility method (not a wrapped set method)
// so you would set it up directly on jQuery, not jQuery.fn. This way, you can
// just call it whenever you want without a wrapped set.
$.typefast();
});
// By wrapping the plugin in an Immediately Invoked Function Expression
// that passes itself the jQuery object, we guarantee the $ will work
(function($){
$.typefast = function(){
$('input').focus(function(){
console.log($(this).attr('id'));
});
}
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">
但是,这里不需要 jQuery 插件。这不是插件的用途,你甚至不是 writing it 根据最佳实践。这不是设置事件处理程序的方法。您需要做的就是为文本框的 focus
事件设置一个事件处理程序:
// Just passing a function directly to the jQuery object is the same
// thing as explicitly setting a callback for document.ready
$(function(){
// This is the function that will be called when any input gets the focus
function typeFast(){
console.log($(this).attr('id'));
}
// Set all input elements to call typeFast when they receive the focus
$('input').on("focus", typeFast);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">
关于javascript - 关注输入触发两次而不是仅一次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44933874/