jQuery UI autocomplete: add a css class to specific items

回眸只為那壹抹淺笑 提交于 2019-11-30 05:14:56

Judging by the custom data and display sample, you'll need to tap into the _renderItem method for autocomplete:

$("input").autocomplete({ ...  }).data("autocomplete")
    ._renderItem = function(ul, item) {
        var listItem = $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a>" + item.label + "</a>")
            .appendTo(ul);

        if (item.personal) {
            listItem.addClass("personal");
        }

        return listItem;
    };

This method is called every time an item is rendered, making it possible to do checks on the item and conditionally apply a class (or do something more complicated).

Here's a working example (without AJAX, but the concept is the same): http://jsfiddle.net/andrewwhitaker/rMhVz/2/

If you are using JQuery UI 1.10 and above you need to change the code to below: i.e ".data("ui-autocomplete")"

$("input").autocomplete({ ...  }).data("ui-autocomplete")
._renderItem = function(ul, item) {
    var listItem = $("<li></li>")
        .data("item.autocomplete", item)
        .append("<a>" + item.label + "</a>")
        .appendTo(ul);

    if (item.personal) {
        listItem.addClass("personal");
    }

    return listItem;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!