我有一个 jQuery“自动建议”类型的搜索框。它使用 Href 填充搜索结果列表,以便用户可以单击列表中的项目以转到相关页面。用户还可以使用箭头键滚动列表以进行选择。我现在要做的是允许用户按 Enter 键转到他们选择的 URL。我有 Enter 键工作,但我不确定我应该如何构建列表或从列表中提取 Href 等。或者我应该有第二个隐藏列表,它只包含纯 URL?
这是迄今为止标记为###的相关部分的代码:
<script>
var results_list = '';
function callback(result) {
results_list.show();
var items = [];
$.each(result, function (i, item) {
items.push("<li><a href='/view/raw/" + item.collection + "/" + item.classname + "/" + item._id + "'>" + item.Title + "</a></li>");
});
results_list.append(items.join(''));
}
var list_selected;
var li = '';
$('.search').each(function () {
$(this).keyup(function (e) {
var search_type = $(this).attr('name');
results_list = $('#' + search_type + '_list');
li = results_list.children();
var key_code = e.keyCode;
if ($.inArray(key_code, [37, 38, 39, 40]) > -1) {
if (e.which === 40) {
if (list_selected) {
list_selected.removeClass('selected');
next = list_selected.next();
if (next.length > 0) {
list_selected = next.addClass('selected');
} else {
list_selected = li.eq(0).addClass('selected');
}
} else {
list_selected = li.eq(0).addClass('selected');
}
} else if (e.which === 38) {
if (list_selected) {
list_selected.removeClass('selected');
next = list_selected.prev();
if (next.length > 0) {
list_selected = next.addClass('selected');
} else {
list_selected = li.last().addClass('selected');
}
} else {
list_selected = li.last().addClass('selected');
}
}
} else {
// ### relevant section ###
if (key_code == 13) { // what to do here??
window.location = list_selected.html();
// ###
} else {
results_list.empty();
var params = {
'search_type': search_type,
'q': $(this).val()
};
if ($(this).val()) {
ajaxThis("search_box", params, callback);
}
}
}
});
});
</script>