[英]Handle enter key press event inside jQuery UI autocomplete
有沒有辦法在jquery自動完成功能中按Enter鍵來處理事件? 如果我點擊下拉結果的項目,我會轉到以下網址
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();
}
});
按鍵的想法沒有錯。 如果您需要備用解決方案,我建議您使用form
標記:
<form action="/users/list" method="get">
<input id="search" name="name">
</form>
如果自動完成菜單未激活 ,表單將在按下輸入時提交。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.