javascript - jquery - 为文本字段 "changing"建立事件? (按键工作,但没有退格事件)

标签 javascript jquery

我有一个“搜索”框,应该能够“实时”搜索数据。现在,如果我将“按键”事件附加到它并更新结果,它会很好用。但是,如果他们按退格键,则不会说明这一点(刷新结果)。

我知道我大概可以解释“退格”键。

但是我是否还遗漏了任何其他可能性?我希望对输入中的文本进行任何更改以触发“事件”或调用刷新功能。

我不想做的一件事是设置“警报”或“计时器”以经常检查它是否已更改。

想法?

最佳答案

为确保在每次更改文本字段后触发数据搜索,您应该在每次 .keyup().keydown() 之后检查文本字段是否已更改

// The following only works for keyboard input, to handle mouse copy / paste
// see the example after this
$(function() {                         // <== Doc ready  

    var inputVal = $("input").val();   // a variable to hold the text
                                       // set it up w the initial value then see 
                                       // if the input value changes.

    $("input").keyup(function() {

        // check for change of the text field after each key up
        if(this.value != inputVal)
        {
            // Do your search, etc.
            // ...

            // Reset the temp value for the next comparison
            inputVal = this.value
        }
    });
});

Try it out with this jsFiddle

为了处理鼠标复制粘贴(Filipe 指出这不适用于上述操作),jQuery 可以选择将多个事件绑定(bind)到一个元素,并且它有一个 paste剪切事件。这些问题是它们在粘贴时立即触发,但在输入框内容实际更改之前,所以我们需要一个超时...事实上,超时对于整个事情来说是一个很好的功能,所以如果用户是快速打字,然后我们等到他们完成:

$(function() {    // <== Doc ready  

    var inputVal = $("input").val(), // a variable to hold the text
                                     // set it up w the initial value then see 
                                     // if the input value changes.

        timer,
        checkForChange = function() {
            var self = this; // or just use .bind(this)

            // we only want to check on the input after the user has settled down,
            // so use a timeout and clear it if another input comes in
            if (timer) { clearTimeout(timer); }

            // check for change of the text field after each key up
            timer = setTimeout(function() {
                if(self.value != inputVal) {
                    // Do your search, etc.
                    $("span").html(parseInt($("span").html(),10) + 1);

                    // Reset the temp value for the next time
                    inputVal = self.value
                }
            }, 250);
        };

    $("input").bind('keyup paste cut', checkForChange);
});

现在我们检查键盘、粘贴和剪切。

Try it out with this jsFiddle


关于javascript - jquery - 为文本字段 "changing"建立事件? (按键工作,但没有退格事件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3971524/

相关文章:

javascript - Jquery mobile值重写toFixed方法

javascript - 防止动态添加 "instance variables"的能力 Javascript OOP

asp.net - 不显眼的 Javascript 富文本编辑器?

javascript - Grunt uglify - 合并文件后更新 src

javascript - onClick 完全删除特定的 DIV

jquery - 根据输入值更新 iframe src

javascript - 如何获取数据表中单元格的属性

javascript - 为什么 HTML 说我的变量没有定义?

javascript - 使用数据表时,取消选中所有复选框不适用于所有页面

javascript - Angularjs 表单验证