jQuery autocomplete and focus event
Mornin' all,
I have troubles to play with jQuery UI autocomplete widget events.
I want to a add a custom class to the parent <li>
of the selected item.
The generated markup looks like :
<li class="result">
<a><span></span></a>
</li>
When an item is focus, jQuery add the class .ui-state-hover
to the <a>
How can I add a class .selected
to the parent <li>
?
I'm trying to do it from a focus
event but I don't know how to access to the parent <li>
.
I looked to the source of jQuery UI and found where and how the .ui-state-hover
is applied but doesn't help.
Here is my code for autocomplete.
/**
* Override the default behavior of autocomplete.data('autocomplete')._renderItem.
*
* @param ul _object_ The conventional ul container of the autocomplete list.
* @param item _object_ The conventional object used to represent autocomplete data.
* {value:'',label:'',desc:'',icon:''}
*/
var renderItemOverride = function (ul, item) {
return $('<li class="result"></li>')
.data("item.autocomplete", item)
.append('<a><span class="name">' + item.label + '</span><span class="type"></span></a>')
.appendTo(ul);
};
$('#live_search').autocomplete({
source: function(request, response) {
$.ajax({
url: "search.json",
dataType: "json",
cache: false,
data: {
term: request.term
},
success: function(data ) {
response($.map(data.contacts, function(item) {
return {
label: item.name || (iterm.firstname + item.lastname),
开发者_开发知识库 value: item.name || (iterm.firstname + item.lastname),
id: item._id
}
}));
}
});
},
appendTo: '.live_search_result_list',
autoFocus: true,
minLength: 2,
focus: function(event, ui) {
},
select: function(event, ui) {
console.log("do a redirection");
}
}).data('autocomplete')._renderItem = renderItemOverride;
})
Any ninja can help ?
How about:
focus: function(event, ui) {
$(".live_search_result_list li.result").removeClass("selected");
$("#ui-active-menuitem")
.closest("li")
.addClass("selected");
},
Then, to remove the selected
class from any li
s when the menu loses mouse focus:
$(".live_search_result_list ul").mouseleave(function() {
$(this).children("li.result").removeClass("selected");
});
Here's a working example: http://jsfiddle.net/andrewwhitaker/4z3SQ/
精彩评论