问题
I am referring to this plugin: http://jqueryui.com/demos/autocomplete/
So the original structure for the results is
<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all">
<li class="ui-menu-item">
<a class="ui-corner-all">item 1</a>
</li>
<li class="ui-menu-item">
<a class="ui-corner-all">item 2</a>
</li>
<li class="ui-menu-item">
<a class="ui-corner-all">item 3</a>
</li>
</ul>
I need to make the links inside to look something like this:
<a class="myclass" customattribute="something"> The item </a>
Please don't tell me the only solution it to edit the plugin because i don't want the same format for all autocompletes on the site.
回答1:
You need to replace the _renderItem
method (for the autocomplete in question):
$("selector").autocomplete({ ... })
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a class='myclass' customattribute='" + item.customattribute + "'>" + item.label + "</a>" )
.appendTo( ul );
};
(assuming the items
in your source
have a property called customattribute
)
As shown in this example: http://jqueryui.com/demos/autocomplete/#custom-data
回答2:
This is also documented in jquery-ui autocomplete documentation at: Jquery-autocomplete.
The trick is:
- Use this jquery extension: github Code
Then in autocomplete option pass
html:true ...autocomplete({ ... html:true ... }
);
Now you can pass html(like <div>sample</div>) in "label" field of JSON output for autocomplete.
If you don't know how to add the plugin to JQuery then:
- Save the plugin(Scott González' html extension) in a js file or download the js file.
- You have already added the jquery-ui autocomplete script in your html page(or the jquery-ui js file). Add this plugin script after that autocomplete javascript file.
Post date: 28th July, 2013
回答3:
You could try add the attributes with the event "open":
$( ".selector" ).autocomplete({
open: function(event, ui) {
var jArrEl = $("a.ui-corner-all");
jArrEl.addClass("myclass");
jArrEl.attr("customattribute","something");
}
});
来源:https://stackoverflow.com/questions/7746679/jquery-autocomplete-custom-html-for-result-listing