我正在尝试使用箭头键导航自动完成下拉列表。
JSON
{
"employees":[
{
"name": "Alex"
},
{
"name": "Alice"
},
{
"name": "Brian"
},
{
"name": "Betsy"
},
{
"name": "Beck"
},
{
"name": "Bob"
},
{
"name": "Brad"
},
{
"name": "Brown"
}
]
}
JQUERY
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style>
.selected{background-color:pink;}
</style>
<script type="text/javascript" src="js/jquery-1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var keyCounter = -1;
jQuery.ajax({
type: "GET",
url: "myjson.json",
dataType: "json",
async: "true",
contentType: "application/x-javascript; charset=utf-8",
cache: "false",
success: function(response){
$("input#myInput").live("keyup", function(e){
var myInputVal = $("input#myInput").val();
var myInputValLen = $("input#myInput").val().length;
$("ul#myList").empty();
for (var x = 0; x < response.employees.length; x++) {
var empName = response.employees[x].name;
if (empName.substring(0, myInputValLen).toLowerCase().search(myInputVal.substring(0, myInputValLen).toLowerCase()) != -1) {
$("ul#myList").append("<li>" + empName + "</li>");
}
}
if (e.keyCode == 40) {
var keyCnter = keyCounter;
var listLen = $("li").length;
if (keyCnter != listLen - 1) {
keyCnter++;
$("li").removeClass("selected");
$("li").eq(keyCnter).addClass("selected");
keyCounter = keyCnter;
}
}
});
}
})
})
</script>
</head>
<body>
<input type="text" width="25" id="myInput">
<ul id="myList" style="margin:0px;"></ul>
</body>
</html>
复制的步骤
如何将计数器重置为-1?
答案 0 :(得分:4)
完全未经测试,但如果按下向下箭头以外的任何其他内容,将它重置为-1会有意义吗?
if (e.keyCode == 40) {
...
} else {
keyCounter = -1;
}