是否可以仅对自动完成下拉列表中返回的部分结果添加样式?
下面的代码工作正常,但是,我想根据 data[x].restricted
的值设置单个结果的样式。当它是 true
时,我仍然想显示这些项目,但在自动完成下拉列表中将它们禁用或变灰。如果 data[x].restricted
是 false
,那么我不想对这些项目应用任何其他样式。
source: function (request, response) {
$.ajax({
url: $("#AutoCompleteCustomerNameUrl").val(),
type: "POST",
dataType: "json",
data: {
srchCus: request.term
},
success: function (data) {
var x, array = [];
for (x in data) {
array.push({
label: (data[x].restricted ? 'Restricted Access - ' : '') + data[x].customerName,
name: data[x].customerFullName
});
}
}
});
}
任何有关如何完成此操作的帮助将不胜感激。
答案 0 :(得分:1)
感觉这不是一个很好的选择,但是您可以通过使用 jQuery 根据文本 content
来定位元素来实现这一点。自动完成建议是作为 <li>
生成的,所以这样的事情可能会起作用:
$('li:contains("Restricted Access")').addClass('grey');
问题是什么时候运行?当然,这些元素是在页面加载后动态添加的,因此必须在创建它们之后 运行 - 您必须根据某些自动完成事件运行它。查看文档中的列表,也许 the open event 是最好的。每当打开菜单时,该事件的处理程序就会运行,因此它可以向所有刚创建的与该选择器匹配的建议添加一个 CSS 类。例如(未经测试):
$("#selector").autocomplete({
// ... your normal autocomplete code ...
open: function(event, ui) {
// Add a CSS class to those suggestions matching the text
$('li:contains("Restricted Access")').addClass('grey');
}
});
我没有测试过这个,因为这不是正确的方法。下面是一个更好、经过测试且有效的选项。
您也可以使用 _renderItem
extension point 执行此操作。如果您检查他们在那里提供的示例,您可以看到它是实际生成 HTML 的函数,该函数显示为您的自动完成建议。如果我们可以自定义它,我们可以做任何事情 - 例如检查项目的详细信息,添加特定的 CSS 类等。
我觉得那些文档不是很清楚,但不难找到使用中的示例,例如 the Custom Data example(@Simon-K 在上面的评论中链接到)展示了如何使用它:
$("#selector").autocomplete({
// ... your normal autocomplete code ...
}).autocomplete("instance")._renderItem = function(ul, item) {
// Here we have complete control of what is returned, and access to
// the items!
return $("<li>").append("<div>" + item.label ...).appendTo(ul);
};
根据您的要求,我们可以这样做:
$("#selector").autocomplete({
// ... your normal autocomplete code ...
}).autocomplete("instance")._renderItem = function(ul, item) {
var style = (item.restricted) ? 'grey' : '';
return $("<li>")
.append("<div class='" + style + "'>" + item.label + "</div>")
.appendTo(ul);
};
然后当然添加一个 CSS 类来设置这些项目的样式:
.grey {
color: #ccc;
}