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

时间:2015-05-13 11:31:24

标签: 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" />

从上面的代码中,第一次加载页面时只有控制台,但在输入框中输入任何内容后,它都无法控制。

2 个答案:

答案 0 :(得分:2)

您无意中绑定了window的{​​{1}}事件。您应该使用onkeyup来绑定每个输入上的单个keyup事件:

&#13;
&#13;
$(this).on
&#13;
$.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();
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在插件中添加bode(H) 事件并将其绑定到当前输入

keyup

<强> Demo

相关问题