我正在尝试遍历一系列项目,看看是否有任何匹配然后显示它们。好吧,如果我输入他们都显示的任何角色。
(sensitive == false ? RegExp('^'+this.value,'i').test(source[i]) : RegExp('^'+this.value).test(source[i]) )
这是我的条件,但是如果this.value
= a
数组中的每个项目(source[i]
)都显示出来。有没有办法让这更严格?
示例
如果是(使用jquery自动完成示例数组)
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
element.addEventListener('keypress', function (e) {
var dd = document.getElementById('fake_dropdown');
for (i = 0; i < availableTags.length; i++) {
var li;
if ((sensitive == false ? RegExp('^' + this.value, 'i').test(availableTags[i]) : RegExp('^' + this.value).test(availableTags[i]))) {
li = document.getElementById('auto_id_' + (i + 1));
li.style.display = "block";
} else {
li = document.getElementById('auto_id_' + (i + 1));
li.style.display = "none";
}
var liLoop = dd.getElementsByTagName('li');
for (var j = 0; j < liLoop.length; j++) {
if (liLoop[j].style.display == "block") break;
else dd.style.display = "none";
}
}
}, false);
更新更多代码
所有这些都显示出来了。为什么是这样?另外,为什么BACKSPACE
不被认为是一个按键,因为如果我点击退格键,它就不会重新评估条件。
答案 0 :(得分:2)
见
el.addEventListener('focus', function (e) {
lastIndex = this;
if (typeof focus == 'function') focus.call(this, this);
}, false);
//use keyup handler since keypress will not be fired for unprintable characters
//don't register the handler inside the focus handler since it can cause multiple event registrations
el.addEventListener('keyup', function (e) {
var dd = document.getElementById('fake_dropdown'),
items = 0;
var top, left, height, width, bottom;
var term = this.value,
//move this out out the for loop
regex = (sensitive == false ? new RegExp('^' + this.value, 'i') : new RegExp('^' + this.value));
for (i = 0; i < source.length; i++) {
var li = document.getElementById('auto_id_' + (i + 1));
if (regex.test(availableTags[i])) {
li.style.display = "block";
items++;
} else {
li.style.display = "none";
}
}
if (items == 0) {
dd.style.display = "none";
} else {
top = el.offsetTop
left = el.offsetLeft;
height = el.offsetHeight;
width = el.offsetWidth;
bottom = top + height;
dd.style.left = left + 'px';
dd.style.top = bottom + 'px';
dd.style.width = width + 'px';
dd.style.display = "block";
}
}, false);
演示:Fiddle