如何使用对象数组作为 jQuery UI AutoComplete 的源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4668206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:41:24  来源:igfitidea点击:

How can I use a array of objects as source for jQuery UI AutoComplete

jqueryjquery-ui

提问by Jiew Meng

If I have a array of objects like

如果我有一组对象,例如

var arrLinks = [
    { key: 1, url: "http://google.com" },
    { key: 2, url: "http://yahoo.com", title: "Yahoo" },
    { key: 2, url: "http://microsoft.com" }
];

Can I use it as the source for autocomplete? I tried implementing in following http://jqueryui.com/demos/autocomplete/#custom-databut didn't get it http://jsfiddle.net/mvNNj/

我可以将其用作自动完成的来源吗?我尝试在以下http://jqueryui.com/demos/autocomplete/#custom-data 中实现但没有得到它http://jsfiddle.net/mvNNj/

回答by karim79

You need to:

你需要:

1 - Actually include jQuery + UI on your test page.

1 - 实际上在您的测试页面上包含 jQuery + UI。

2 - Incorporate the use of 'labels' which the Autocompleter uses to find matches:

2 - 结合使用 Autocompleter 用于查找匹配项的“标签”:

$(function() {
    var arrLinks = [
        {
        key: 1,
        url: "http://google.com",
        label: 'google'},
    {
        key: 2,
        url: "http://yahoo.com",
        title: "Yahoo",
        label: 'yahoo'},
    {
        key: 2,
        url: "http://microsoft.com",
        label: 'microsoft'}
    ];
    $("input[name=url]").autocomplete({
        source: arrLinks
    }).data("autocomplete")._renderItem = function(ul, item) {
        return $("<li>").data("item.autocomplete", item).append("<a>" + item.url + "</a>").appendTo(ul);
    };
});

Your test page, working.

你的测试页,工作。