簡體   English   中英

如何修改這個 JQuery 函數

[英]How to modify this JQuery function

我正在使用 jquery.autocomplete 來顯示搜索建議。 現在該函數獲取該值並將其插入到“/collections/”后面。

我喜歡給每個標簽一個自定義 url。 如果有人能告訴我如何實現,那就太棒了。

 $(function(){ var tags = [ { value: 'product1' }, { value: 'product2' }, { value: 'product3' }, { value: 'product4' } ]; $('#autocomplete1').autocomplete({ lookup: tags, lookupFilter: function (suggestion, originalQuery, queryLowerCase) { return suggestion.value.toLowerCase().indexOf(queryLowerCase) === 0; }, onSelect: function (suggestion) { document.location.href = "/collections/" + $(this).val() } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.2.24/jquery.autocomplete.js"></script> <form method="get" id="searchbar" action="/search"> <button type="submit" value="Search"> <span class="icon-search"></span> </button> <input type="text" name="q" autocomplete="off" id="autocomplete1" placeholder="Search"/> </form>

所以像這樣:

$(function(){
  var tags = [      
    { value: 'product1', url: '/collections/product1' },
    { value: 'product2', url: '/collections/product2b' },
    { value: 'product3', url: '/collections/product3a' },
    { value: 'product4', url: '/collections/product4b' }, 
  ];

為此,您可以使用ui.item.{parameter} ,因此在您的情況下, ui.item.url

在這種情況下,當您單擊自動完成中的值時, ui.item設置為:

[object Object] {
  label: "product1",
  url: "/collections/product1",
  value: "product1"
}

然后您可以輕松選擇網址並指向文檔位置

 $(function() { var availableTags = [ { url: '/collections/product1', value: 'product1' }, { url: '/collections/product2b', value: 'product2' }, { url: '/collections/product3a', value: 'product3' }, { url: '/collections/product4b', value: 'product4' } ]; $( "#autocomplete1" ).autocomplete({ source: availableTags, select: function (event, ui) { document.location.href = ui.item.url; } }); });
 <!DOCTYPE html> <html> <head> <link href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src="https://code.jquery.com/jquery-1.11.3.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="ui-widget"> <label for="tags">Tags: </label> <input type="text" name="q" autocomplete="off" id="autocomplete1" placeholder="Search"/> </div> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM