我有一个“搜索”框,应该能够“实时”搜索数据。现在,如果我将“按键”事件附加到它并更新结果,它会很好用。但是,如果他们按退格键,则不会说明这一点(刷新结果)。
我知道我大概可以解释“退格”键。
但是我是否还遗漏了任何其他可能性?我希望对输入中的文本进行任何更改以触发“事件”或调用刷新功能。
我不想做的一件事是设置“警报”或“计时器”以经常检查它是否已更改。
想法?
最佳答案
为确保在每次更改文本字段后触发数据搜索,您应该在每次 .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
}
});
});
为了处理鼠标复制粘贴(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);
});
现在我们检查键盘、粘贴和剪切。
关于javascript - jquery - 为文本字段 "changing"建立事件? (按键工作,但没有退格事件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3971524/