我无法弄清楚如何使箭头键适用于我的自动提示框。我知道我需要在我的代码中添加这样的内容:
var keynum = 0;
if(window.event) { keynum = e.keyCode; } // IE
else if(e.which) { keynum = e.which; } // Netscape/Firefox/Opera
if(keynum === 38) { // up
//Move selection up
}
if(keynum === 40) { // down
//Move selection down
}
if(keynum === 13) { // enter
//Act on current selection
}
但我不知道如何使用我的代码。有人可以帮我弄清楚我的代码会如何。当我按向下箭头时,我希望突出显示的结果在按下向上箭头时向下移动一个向上。继承我的代码:
</ul>
<div class="input-wrapper">
<input type="text" class="autosuggest" value="Type in a city or town" onblur="onBlur (this)" onfocus="onFocus(this)" > <input type="submit" value="Search">
<div class="dropdown">
<ul class="result"></ul>
</div>
</div>
$(document).ready(function() {
$('.autosuggest').keyup(function() {
var search_term = $(this).attr('value');
$.post('php/search.php', { search_term: search_term }, function(data) {
$('.result').html(data);
$('.result li').click(function(){
var result_value = $(this).text();
$('.autosuggest').attr('value', result_value);
$('.result').html('');
});
});
});
});
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
答案 0 :(得分:0)
我注意到你已经在使用jQuery了。如果可能,jquery-ui库已经提供了您想要的键盘功能。包括ajax数据源。在jQuery-ui demo here中输入'j'并使用箭头键。然后查看文档以获取您的ajax帖子。
$(function(){
$(".autosuggest").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/php/searchToJSON.php",
dataType: "json",
data: {
search_term: request.term
},
success: function( data ) {
//this maps your serverside /searchToJSON.php to the {label:something, value:somethingElseMaybe} that jquery-ui autocomplete needs
response( $.map( data.SomeNameYouPick, function( itemWithinSomeNameYouPick ) {
return {
label: itemWithinSomeNameYouPick.labelToShowForOneItem,
value: itemWithinSomeNameYouPick.valueWhenSelectedForOneItem
}
}));
}
});
},
minLength: 2
});
});