javascript - 如何将 keyup 事件绑定(bind)到 jQuery 插件

标签 javascript jquery jquery-plugins

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

相关文章:

javascript - 找一个工具可以在我的电脑上运行javascript

javascript - 如何使用原型(prototype)创建类而不使用 "new"和 "this"

javascript - 如何首先将输入字段设置为只读,然后单击 vuejs 中的按钮使其可编辑?

javascript - 无法在框架中加载 youtube api

javascript - 如何使用jquery从数据库创建复选框列表数据

javascript - 是否有自动 jQuery 插件更新程序?

javascript - 将 JQuery Promises 数组转换为数组的 JQuery Promise 的最干净的方法是什么?

javascript - 在仍然能够导航页面的同时放大元素

javascript - 调整窗口大小/最大化窗口时背景/内容下半部分消失

jquery globalcss IE 不透明度