如何将 keyup 事件绑定到 jQuery 插件

How to Bind keyup event to jQuery plugin

我正在尝试创建 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" />

从上面的代码来看,它只在第一次加载页面时控制台,但是在输入框中输入任何内容后它不会''控制台。

在插件中添加 keyup 事件并将其绑定到当前输入,

$.fn.search_panel = function () {
    if ($(this).prop("tagName").toLowerCase() == 'input') {
         $(this).keyup(function () {
            var input_str = $.trim($(this).val());
            console.log($(this));
            console.log(input_str);
         });
    }  
};

Demo

您无意中绑定了 windowonkeyup 事件。您应该使用 $(this).on 来绑定到每个输入的单个 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>