代码之家  ›  专栏  ›  技术社区  ›  BenAlabaster

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

  •  0
  • BenAlabaster  · 技术社区  · 14 年前

    I've got a list that's got a mouseover 事件绑定:

    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);
    });
    //...
    

    在我的 鼠标开关 事件 event.target returns the anchor as expected, but I need the index of the li 祖先(在 ul ) of the anchor I'm hovering over.

    Given that the content of the could be more complex than just the anchor, does jQuery provide a simple way of finding that out?

    也就是说,我徘徊在某个后代 li[0] li[4] 等。。。

    1 回复  |  直到 14 年前
        1
  •  1
  •   Community CDub    7 年前

    你可以使用 .index() ,像这样:

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

    来自文档:

    如果 索引() 对元素集合调用,并传入dom元素或jquery对象, 索引() 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 <理工大学; containing the link in that collection.


    Alternatively, instead of using event.target you can do it a bit more cleanly with .delegate() ,像这样:

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

    在这种情况下, this 指的是 <理工大学; 所以正常 索引() 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 < > , 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 .