代码之家  ›  专栏  ›  技术社区  ›  Matt McCormick

jQuery索引()的问题

  •  10
  • Matt McCormick  · 技术社区  · 16 年前

    HTML:

    <div id="rating_boxes">
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
    </div>
    

    jQuery:

    $("img.ratingbox").hover(function() {
        var index = $(this).parent().index(this);
                // have also tried $("#rating_boxes").index(this);
                // and $("#rating_boxes").index($(this));
                // and $(this).parent().index($(this));
        alert(index);
        $(this).attr('src', '/img/ratingbox-selected.gif');
    }, function() {
        $(this).attr('src', '/img/ratingbox.gif');
    });
    
    3 回复  |  直到 16 年前
        1
  •  25
  •   Russ Cam    16 年前

    我倾向于避免使用 index()

    $(this).prevAll().length
    

    获取索引。使命感 size() prevAll() length 属性,因此我更喜欢直接使用length并跳过额外的函数调用。

    例如

    $("img.ratingbox").hover(function() {
        var index = $(this).prevAll().length;
        alert(index);
        $(this).attr('src', '/img/ratingbox-selected.gif');
    }, function() {
        $(this).attr('src', '/img/ratingbox.gif');
    });
    

    在jQuery1.4中,您只需调用 索引() 在jQuery对象上获取对象中第一个元素的索引。

        2
  •  12
  •   user229044    16 年前

    index() 返回给定元素的索引以及元素列表,而不是在父元素中。要查找单击图像的索引,需要查找所有图像,而不是 父母亲

    // Find all the images in our parent, and then find our index with that set of images
    var index = $(this).parent().find("img").index(this);
    

    在第二个示例中,您还使用了id选择器而不是类选择器。而不是

    $("#rating_boxes").index($(this)); // your way - select by ID
    

    你想要

    $(".rating_boxes").index(this); // select by class
    
        3
  •  6
  •   Tatu Ulmanen    16 年前

    var index = $(this).prevAll('img').size();
    

    即,计算该元素之前的img元素数量。index方法要求您首先选择父元素,然后选择其中的所有img元素。这稍微快一点。

        4
  •  0
  •   Olu    6 年前

    var index=$(this).prevAll().length;

    不会起作用,因为它给出了与使用相同的答案

    var index=$(this.parent().find(“img”).index(this);

    我刚刚用这两种方法解决了我的问题。