jQuery UI 自动完成:向特定项目添加 css 类 [英] jQuery UI autocomplete: add a css class to specific items
问题描述
我正在使用 Jquery UI 的自动完成小部件,并且我正在获取要通过回调显示的项目,如参考中所述.
I am using Jquery UI's autocomplete widget and I am fetching the items to display through a callback as described in the reference.
我有一个用例,我需要展示我从服务器检索到的一些项目与其他项目略有不同,以便用户了解这些项目之间存在差异.就我而言,有些项目是个人的",有些是全球的".
I have a use-case where I need to present some of the items that I retrieve from the server slightly differently than others, so that the user understands there is a difference between these items. In my case, some of the items are 'personal', and some are 'global'.
我想让个人"项目脱颖而出,向它们添加 CSS 类,使它们的背景略有不同.
I would like to let the 'personal' items stand out by adding a CSS class to them so that they have a slightly different background.
这可能吗?我在参考文档中看到存在一个插件,它允许我在项目"中放置任意 HTML,但是当我真正需要做的只是添加一个类(在某些情况下)时,我觉得这不是最佳选择.
Is this possible? I have seen in the reference documentation that an addon exists that allows me to put arbitrary HTML in the 'items', but I feel that is suboptimal when all I really need to do is add a class (in some cases).
我想我最终会得到这样的结果:
I think i would end up with something like this:
$("#myElement").autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
var baseUrl = '/getItems.php'
$.getJSON(baseUrl, req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
var entry = new Object();
if (val.personal == true){
// add some css class somehow?
}
entry.id = val.id;
suggestions.push(entry);
});
//pass array to callback
add(suggestions);
});
},
});
推荐答案
根据 自定义数据判断并显示示例,您需要使用 _renderItem
方法进行自动完成:
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).
这是一个工作示例(没有 AJAX,但概念是相同的):http://jsfiddle.net/andrewwhitaker/rMhVz/2/
Here's a working example (without AJAX, but the concept is the same): http://jsfiddle.net/andrewwhitaker/rMhVz/2/
这篇关于jQuery UI 自动完成:向特定项目添加 css 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!