有没有办法在jQuery自动完成功能中处理按Enter键的事件?如果我点击下拉结果的项目,将转到以下URL。
window.location.href = '/user?userId=' + ui.item.userId;
在函数的选择部分中它运行良好。但是,如果我需要在键入一些字母并显示下拉结果列表,但我没有点击其中任何一个项目,而只是按下回车键时更改我的 url,我该怎么处理呢?
$('#search').autocomplete({
source: function(request, response) {
$.ajax({
url: "/search/users",
data: {
query: request.term
},
success: function(data) {
var transformed = $.map(data, function(el) {
return {
name: el.name,
email: el.email
};
});
response(transformed);
},
error: function() {
response([]);
}
});
},
select: function(event, ui) {
window.location.href = '/user?userId=' + ui.item.userId;
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
var $a = $("<a></a>").append(item.name);
highlightText(this.term, $a);
return $("<li></li>").append($a).appendTo(ul);
};
我尝试了这个方法,但我想知道是否有更好的解决方案。
$('#search').on('keypress', function(e) {
if (e.which == 13 && $(this).val()) {
window.location.href = '/users/list?name=' + $(this).val();
}
});