Javascript jquery-为文本字段构建事件;改变;?(除无退格事件外,按键有效)
我有一个“搜索”框,应该可以“实时”搜索数据。现在,如果我将“keypress”事件附加到它并更新结果,它的效果相当好。但是,如果他们按backspace键,这并不能解释这一点(刷新结果) 我知道我可能可以解释“backspace”键 但我是否错过了任何其他可能性?我希望输入中文本的任何更改都会触发“事件”或调用刷新功能 我不想做的一件事是设置“警报”或“计时器”,以便经常检查它是否发生了变化Javascript jquery-为文本字段构建事件;改变;?(除无退格事件外,按键有效),javascript,jquery,Javascript,Jquery,我有一个“搜索”框,应该可以“实时”搜索数据。现在,如果我将“keypress”事件附加到它并更新结果,它的效果相当好。但是,如果他们按backspace键,这并不能解释这一点(刷新结果) 我知道我可能可以解释“backspace”键 但我是否错过了任何其他可能性?我希望输入中文本的任何更改都会触发“事件”或调用刷新功能 我不想做的一件事是设置“警报”或“计时器”,以便经常检查它是否发生了变化 想法?为了确保每次更改文本字段后都会触发数据搜索,您应该检查每次.keyup()或.keydown()
想法?为了确保每次更改文本字段后都会触发数据搜索,您应该检查每次
.keyup()
或.keydown()
现在我们检查键盘、粘贴和剪切
看看(关于HTML5中不同类型的
输入元素共享的事件行为)。特别是,change
事件应该执行您想要的操作。(无论如何,这几十年中的一年。)处理此事件至少应该是安全的,即使许多浏览器还不支持它。更改事件只在文本字段模糊时触发,因此在这种情况下它不会真正起作用。From=>对于选择框、复选框和单选按钮,当用户使用鼠标进行选择时会立即触发事件,但是对于其他元素类型,事件会延迟到元素失去焦点为止。
@FilipeGiusti添加了第二个处理粘贴和剪切的片段==>
// 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
}
});
});
$(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);
});