I’ve got a list that’s got a mouseover event bound:
myObject = function()
{
this.listTemplate = $("<ul></ul>")
.mouseover(function(event) {
//Do mouse over stuff
})
.click(function(event) {
//Do click stuff
});
//...more stuff
}
Later on in my code, I’m populating this list with items returned by an Ajax call, which all works swimmingly…
In the Ajax success method:
//...
$(items).each(function(item) {
$("<li />").append("<a />").text(item.value)
.appendTo(templateList);
});
//...
In my mouseover event, the event.target returns the anchor as expected, but I need the index of the li ancestor (within the ul) of the anchor I’m hovering over.
Given that the content of the li could be more complex than just the anchor, does jQuery provide a simple way of finding that out?
i.e. I’m hovering over some descendent of li[0] or li[4] etc…
You can use
.index(), like this:From the docs:
This goes up to the
<ul>, gets it’s children (the<li>elements), and gets the index of the<li>containing the link in that collection.Alternatively, instead of using
event.targetyou can do it a bit more cleanly with.delegate(), like this:In this case,
thisrefers to the<li>so the normal.index()call just gets it’s index relative to it’s siblings, if it’s an option…it’s a bit simpler route to take.Last, kind of tangential to the question, you don’t need to encode
<and>, you can just have:If you’re doing this for XHTML/validation purposes, just wrap your script in
CDATAto validate correctly.