我正在尝试添加css
根据条件列出项目,如果列表项label
文本包含+
我需要添加红色否则我只需要添加黄色背景色。
我差点儿,但我无法在dynamic data coming form server
函数中访问open
。
代码:
$("#project").autocomplete({
minLength: 0,
source: function (request, response) {
//In success of ajax call i fill request(projects)
response(projects);
},
open: function (event, ui) {
var len = $('.ui-autocomplete > li').length;
//I can access projects here but i need filtered data list coming from server which is passed to response callback
$('.ui-autocomplete > li').css("background-color", "yellow");
for (var i = 0; i < len; i++) {
// Here i use indexof('+') on each list item's label text and apply css but how to get the list here ??
}
$('#count').html('Founded ' + len + ' results');
}
});
检查小提琴 here
答案 0 :(得分:3)
您可以使用css
方法和函数根据文本内容返回颜色:
open: function (event, ui) {
$('.ui-autocomplete > li').css("background-color", function() {
return $(this).text().indexOf('+') > -1 ? 'red' : 'yellow';
});
$('#count').html('Founded ' + len + ' results');
}
演示: http://jsfiddle.net/DZ9zU/35/
我还建议设置一个类名而不是内联css样式,这样可以在样式方面提供更好的灵活性。
open: function (event, ui) {
$('.ui-autocomplete > li:contains(+)').addClass('red');
$('#count').html('Founded ' + len + ' results');
}
使用CSS规则:
.ui-autocomplete > li {
background-color: yellow;
}
.ui-autocomplete > li.red {
background-color: red;
}
答案 1 :(得分:1)
自定义项目显示的另一种方法是使用_renderItem
$("#project").autocomplete({
minLength: 0,
source: function (request, response) {
//In success of ajax call i fill request(projects)
response(projects);
},
open: function (event, ui) {
//do what else you want to do
}
}).data('autocomplete')._renderItem = function (ul, item) {
return $("<li>")
.attr("data-value", item.value)
.addClass(/\+/.test(item.label) ? 'plus' : '')
.append(item.label)
.appendTo(ul);
};
演示:Fiddle