I'd like to change the color of proposed voices following data reported on source xml file. My code may explain my problem better:
$("#search_input").autocomplete({
source: function(req, add){
//pass request to server
$.get(stringa, req, function(xml) {
var dato = $("contratto", xml).map(function() {
return {
label: $( "id", this ).text()+ ", "+ $( "nominativo", this ).text(),
value: $( "id", this ).text(),
cls: $("class", this).text()
};
}).get();
//pass array to callb开发者_JS百科ack
add(dato);
});
},
minLength: 0,
select: function( event, ui ) {
$("#search_input").val(ui.item.label);
$("#hidden_contratto").val(ui.item.value);
//$(".ui-menu-item >a").css("color", "red");
},
open: function(event, ui) {
switch (ui.item.cls)
{
//here must change color to propose if eoncontered cls=red
case "red" :
$(".ui-autocomplete li.ui-menu-item a").css({"color": "red", "text-decoration": "line-through"});
break;
}
}
});
here source xml:
<contratto>
<id>M12125</id>
<nominativo>my name</nominativo>
<class>red</class>
</contratto>
In firebug I get this error: ui.item is undefined
After several attemps I found my solution!
I coverted class in a number and correct my code in this way:
open: function( event, ui ) {
var voce="";
var v="";
$("li > a").each(function(){
v=$(this).text();
voce=v.split(",");
if (voce[2]==1)
$(this).css({"color": "green", "text-decoration": "underline"});
if (voce[2]==2)
$(this).css({"color": "red", "text-decoration": "line-through"});
$(this).text(voce[0]+", "+voce[1]);
});
}
I hope that this will help someone!
ciao h.
,open: function(e, ui) {
var data = $(this).data('autocomplete');
data.menu.element.find('li').each(function() {
var $this = $(this);
var matched = data.term;
var rest = $this.text().replace(matched, '');
var template = $('<span/>', {
'class': 'ui-found',
'text': matched
}).after($('<span/>', {
'text': rest
}));
$this.html(template);
});
}
The open event does not help (http://api.jqueryui.com/1.11/autocomplete/#event-open - "Note: The ui object is empty but included for consistency with other events."
You need to extend original widget and override the _renderItem() function
$.widget("custom.myAutocomplete", $.ui.autocomplete, {
//since now is it copy of autocomplete widget just with different name
//lets override:
_renderItem: function (ul, item) {
let result = $("<li>")
.attr("data-value", item.value)
.append(item.label)
.appendTo(ul);
//here comes the customization
if ("red" === item.cls) {
result.css('color', "red");
}
return result;
}
});
and then you initialize this new widget, not the original:
$("#search_input").myAutocomplete({
//....source and minLengt
Links:
- http://learn.jquery.com/jquery-ui/widget-factory/extending-widgets/
- http://api.jqueryui.com/1.11/autocomplete/#method-_renderItem
精彩评论