我有一个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>
答案 0 :(得分:2)
if ( key_code == 13 && $('.selected').length > 0 ) { // Make sure there's a selection
var selected_item = $('li.selected:first a'); // select li and a
// Two options:
// A.) Make sure the li a's href is an absolute path so you can do:
window.location = selected_item.attr('href');
// B.) Keep the relative href, trigger a click on the element:
$(selected_item).trigger('click');
}