开发者

How can I get the index of an ancestor within another ancestor?

开发者 https://www.devze.com 2023-01-04 15:33 出处:网络
I\'ve got a list that\'s got a mouseover event bound: myObject = function() { this.listTemplate = $(\"<ul></ul>\")

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:

.mouseover(function(e) {
  var i = $(e.target).closest('ul').children().index($(e.target).closest('li'));
})

From the docs:

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

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.target you can do it a bit more cleanly with .delegate(), like this:

$("&lt;ul&gt;&lt;/ul&gt;").delegate('li', 'mouseover', function() {
  var index = $(this).index();
})

In this case, this refers 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:

$("<li />").append("<a />").text(item.value)

If you're doing this for XHTML/validation purposes, just wrap your script in CDATA to validate correctly.

0

精彩评论

暂无评论...
验证码 换一张
取 消