我正在尝试使用 .keypress 过滤数据。我当前的方法是从 .keypress 捕获数据并传递给我的过滤函数。我成功返回以字母开头的数据。因此,如果我在字段中输入 A,它将返回所有以 A 开头的猫。我想通过输入更多字母来缩小搜索范围,并使其每次更新。这里有一个简单的解决方案吗?这是代码
//从按键中检索数据
$("input").keypress(function (e) {
if (e.which !== 0 && e.charCode !== 0) {
var criteria = String.fromCharCode(e.keyCode|e.charCode);
}
$.getJSON('cats.json', function(cats) {
filterCats(cats, criteria);
});
});
//过滤函数
function filterCats(cats, criteria){
$.getJSON('cats.json', function(cats) {
//var filteredData = cats.filter(function(c){return c.breed.toUpperCase().indexOf(criteria.toUpperCase()) !== -1;});
var filteredData = cats.filter(function(c){return c.breed.toUpperCase().indexOf(criteria.toUpperCase()) === 0 ;});
renderData(filteredData);
});
}
最佳答案
正如其他人提到的,keyup
更好,因为它在释放按键后触发。
keydown
Fires when the user depresses a key. It repeats while the user keeps the key depressed.
keypress
Fires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed.
keyup
Fires when the user releases a key, after the default action of that key has been performed.
以上来自http://www.quirksmode.org/dom/events/keys.html
正如其他答案所述,每次按键后立即运行代码可能会导致向服务器发送大量请求。
相反,尝试通过超时来限制它。
var timeout, criteria;
$('input').keyup(function(e) {
clearTimeout(timeout);
timeout = setTimeout(function() {
criteria = this.value;
$.getJSON('cats.json', function(cats) {
filterCats(cats, criteria);
});
}.bind(this), 125);
});
关于javascript - 使用 .keypress 过滤数据 - 无插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32123894/