[英]Enter to select and activate href link
我已經用jquery設置了自動完成搜索欄。 當我輸入搜索詞的一部分時,會彈出建議,當我單擊建議時,我將被重定向到一個新的(建議的)頁面。
我遇到的問題是,當我鍵入搜索詞的一部分或完整搜索詞時,沒有任何動作。
我想要的是:當我輸入搜索詞或搜索詞的一部分並按Enter時,我將重定向到第一個建議的頁面。 當我將鼠標懸停在建議上方時,請立即按Enter鍵,第一個建議就會出現在搜索欄中。
我該怎么辦?
JavaScript代碼:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/black-tie/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
$(function() {
var projects = [{
label: "Bitcoin (BTC)",
icon: "./alt/alt_logo/bitcoin.png",
href: "./alt/alt_info/bitcoin.html"
}, {
label: "Ethereum (ETH)",
icon: "./alt/alt_logo/ethereum.png",
href: "./alt/alt_logo/bitcoin.png"
}, {
label: "Litecoin (LTC)",
icon: "./alt/alt_logo/litecoin.png",
href: "./alt/alt_logo/bitcoin.png"
}, {
label: "Cardano (ADA)",
icon: "./alt/alt_logo/cardano.png",
href: "./alt/alt_logo/bitcoin.png"
}];
$(".field_values").autocomplete({
source: projects,
create: function() {
$(this).data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.append('<a href="' + item.href + '"><img class="icon" src="' + item.icon + '" />' + item.label + '<br>' + '</a>')
.appendTo(ul);
};
}
});
});
PS:不要介意var projects
href
錯誤
編輯:
當我通過按Enter或單擊按鈕提交表單時。 頁面會重新加載,但保持在同一頁面上。
HTML:
<div class="searchbar">
<form id="submitsearch">
<input class="field_values" id="autocomplete" placeholder="Search..."/>
<button type="submit" id="searchbutton" class="icon" ><i class="fa fa-search"></i></button>
</form>
</div>
我還嘗試了<form action="./js/searchbar.js">
但這只是將我發送到顯示了JavaScript的網頁
您需要將autoFocus: true,
添加到autocomplete
,以使其變為:
$("#field_values").autocomplete({
autoFocus: true,
source: projects,
這僅將數據放入表單字段。
要處理數據,您需要執行以下操作:
form
標簽中 確保您在表單中有一個提交按鈕
然后,您將可以按Enter鍵填寫該字段,並且您將不得不再次按Enter鍵以提交表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.