如何在 Jquery 中使用方向键
我试图用这个来模仿 Google 建议列表:
function el(tid) {
return document.getElementById(tid);
}
function addScript(u) {
var head = document.getElementsByTagName('head')[0],
sc2 = document.createElement('script');
sc2.src = u;
head.appendChild(sc2);
setTimeout(function () {
head.removeChild(sc2);
sc2 = null;
}, 600);
} //end addScript()
function suggest(data) {
var sel = el("test");
sel.innerHTML = '';
for (x = 0; x < data[1].length; x++) {
sel.innerHTML += '<li class="uli" >' + data[1][x][0] + '</li>';
}
}
el("inp").onkeyup = function () {
addScript("http://www.google.nl/complete/search?callback=suggest&q=" + this.value);
};
问题是我希望能够使用箭头键进入建议列表,其次我想在输入字段中显示“当前”建议值。所以我使用 Jquery 尝试了类似的操作:
$("#inp").live("keydown", function (e) {
var curr = $('#test').find('.current');
if (e.keyCode == 40) {
if (curr.length) {
$(curr).attr('class', 'uli');
curr = $(curr).next();
}
if (curr.length) {
curr.attr('class', 'uli current');
} else {
$('#center li:first-child').attr('class', 'uli current');
}
}
if (e.keyCode == 38) {
if (curr.length) {
$(curr).attr('class', 'uli');
curr = $(curr).prev();
}
if (curr.length) {
curr.attr('class', 'uli current');
} else {
$('#center li:last-child').attr('class', 'uli current');
}
}
$("#inp").live("keydown", function (e) {
var search_terms = $('li.current').text();
if (e.keyCode == 40) {
$('#inp').val(search_terms);
}
if (e.keyCode == 38) {
$('#inp').val(search_terms);
}
它不起作用,因为(我认为..)“当前”建议立即被前面的代码请求。 我已将所有内容放在这里: JS Bin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么要重新造轮子?
jQuery UI 自动完成
或者查看其他plugins
您的代码的问题是,当您调用以获取值时,您需要取消箭头按键。
另外,当您使用 jQuery 时,
el("inp")
是什么意思?我期望看到$("foo").keyup( function(){} );
Why recreate the wheel?
jQuery UI Autocomplete
Or look at other plugins
The problem with your code is you need to cancel out the arrow keypresses when you call to get the values.
Also what is with
el("inp")
when you are using jQuery? I expected to see$("foo").keyup( function(){} );