我正在尝试创建 jQuery 插件,它需要在输入标签的按键上触发。 但是,不知何故它不起作用:(
到目前为止我已经尝试过:
JS:
$.fn.search_panel = function() {
if($(this).prop("tagName").toLowerCase() == 'input'){
var input_str = $.trim($(this).val());
console.log($(this));
onkeyup = function(){
console.log(input_str);
}
}
};
插件初始化
$(document).ready(function(){
$('input').search_panel();
});
HTML:
<input type="text" />
从上面的代码来看,它仅在页面首次加载时进行控制台,但在输入框中输入任何内容后,它不会进行控制台。
最佳答案
您无意中绑定(bind)了窗口
的onkeyup
事件。您应该使用 $(this).on
来绑定(bind)到每个输入上的单独 keyup 事件:
$.fn.search_panel = function() {
// Iterate all elements the selector applies to
this.each(function() {
var $input = $(this);
// Can probably make this more obvious by using "is"
if($input.is("input")){
// Now bind to the keyup event of this individual input
$input.on("keyup", function(){
// Make sure to read the value in here, so you get the
// updated value each time
var input_str = $.trim($input.val());
console.log(input_str);
});
}
});
};
$('input').search_panel();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input><input><input><input>
关于javascript - 如何将 keyup 事件绑定(bind)到 jQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30213528/