簡體   English   中英

使用 url 從 jQuery UI 自動完成獲取列表選項

[英]Get list options from jQuery UI autocomplete with url

我的元素是一個 jQuery 自動完成元素,它從 URL 獲取其選項:

$element.autocomplete({
    source: '/mysearchurl',
    open: function () {
        //...
    },
    response: function (event, ui) {
        //...
    },
    select: function (event, ui) {
        //...
    }
});

它按預期工作:用戶輸入一些字符,並在下拉列表中顯示匹配的值。

我現在想要的是,在我的 Javascript 中,從列表中獲取選項,最好是從 URL 中獲取的相同 JSON。 我可以嘗試通過這樣的方式從元素中收集它們:

$($element.data('ui-autocomplete').menu.element[0].list.childNodes).each()

但也許有更好的方法?

我建議在內部使用帶有 Ajax 調用的函數:

 $("#autocomplete").autocomplete({ source: function(request, response) { var el = this.element; var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i"); $.ajax({ url: "https://api.myjson.com/bins/qnhcd", type: "GET", contentType: "application/json", dataType: "json", success: function(data, textStatus, jqXHR) { var selection = data.filter(function(item) { if (matcher.test(item.value)) return item.value; }); el.data("source", selection); response(selection); } }); } }); $( "#autocomplete" ).on( "autocompleteresponse", function( event, ui ) { refreshList(); }); refreshList = function() { var source = $("#autocomplete").data("source"); console.log("refreshList", source); $("#list").empty(); if (source) { for (var i in source) { $("#list").append("<li>" + source[i].value + "</li>") } } else { $("#list").append("<li>No options</li>") } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" /> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <label for="autocomplete">Select a programming language: </label> <input id="autocomplete"> <br> <button onclick="refreshList()"> refresh list </button> <br> <ol id="list"> </ol>

這是一個 jsfiddle: http : //jsfiddle.net/beaver71/svLsw13f/

暫無
暫無

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

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