jquery - 为文本字段“更改”构建事件? (按键工作除了没有退格事件)

时间:2010-10-19 18:38:05

标签: javascript jquery

我有一个“搜索”框,应该能够“实时”搜索数据。现在,如果我将“keypress”事件附加到它并更新结果,它的效果非常好。但是,如果按退格键,则不会考虑退格(刷新结果)。

我知道我可能会考虑“退格”键。

但我错过了其他任何可能性吗?我希望输入中任何更改文本以触发“事件”或调用刷新函数。

我不想做的一件事就是设置“闹钟”或“定时器”,以便每次都经常检查一下。

想法?

2 个答案:

答案 0 :(得分:2)

为确保您在每次更改文字字段后触发数据搜索,您应检查每个.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可以选择将多个事件绑定到一个元素,它有一个pastecut事件。这些问题是它们会在粘贴时立即触发,但在输入框内容实际更改之前,所以我们需要超时...事实上,超时对于整个事情来说是一个很好的功能,所以如果用户是快速打字,然后我们等到他们完成:

$(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


答案 1 :(得分:0)

查看Common event behaviors(这是关于HTML5中不同类型的input元素共享的事件行为)。特别是,change事件应该做你想要的。 (无论如何,这几十年中的一个。)至少应该安全地处理这个事件,即使很多浏览器还不支持它。