【问题标题】:Why doesn't index() working as expected为什么 index() 不能按预期工作
【发布时间】:2013-04-06 16:27:05
【问题描述】:

HTML:

<div class="div1">Div 1</div>
<div class="div2">Div 2</div> 
<div class="div3">Div 3</div> 
<div class="div4">Div 4</div> 

<div class="test">Test</div>
<br />
<div class="test">Test</div>
<br />
<div class="test">Test</div> 
<br />
<div class="test">Test</div>
<br />

Jquery:

$(".test").each(function(){
    var i = $(this).index();
    alert(i);
});

Fiddle Demo

我希望结果是0, 1, 2, 3,但为什么输出是4, 6, 8, 10

【问题讨论】:

    标签: jquery


    【解决方案1】:

    为什么输出是4, 6, 8, 10

    $(this).index() 返回元素相对于其兄弟的索引,而不是相对于选定元素的索引。 br.divX 元素也是兄弟元素!

    看起来像你想要的:

    var $tests = $(".test");
    
    $tests.each(function(){
        var i = $tests.index(this);
        alert(i);
    });
    

    或更简单:

    $(".test").each(function(i){
        alert(i);
    });
    

    【讨论】:

      【解决方案2】:

      轻松修复 - .each 支持索引:

      $(".test").each(function(idx){
          alert(idx);
      });
      

      【讨论】:

        【解决方案3】:

        你想做的是这样的:

        $(".test").each(function(i) {
            alert(i);
        });
        

        .index() 返回相对于其兄弟的索引。

        【讨论】:

          【解决方案4】:

          index() 给出元素相对于其兄弟元素的索引。具有文本类的第一个 div 是第 5 个元素,索引为 4,br 位于 5 索引处,下一个具有类 test 的 div 具有索引 6,依此类推。我们可以通过下面的demo查看每个元素的索引

          Live Demo

          $("#parent1 *").each(function () {
              alert("TagName >> " + this.tagName + ", Index >> " + $(this).index() + ", Text " + $(this).text());
          });
          

          如果没有参数传递给 .index() 方法,则返回值为 一个整数,指示第一个元素在 相对于其兄弟元素的 jQuery 对象,Reference

          【讨论】:

            【解决方案5】:

            您必须使其与您正在测试的对象相关。使用:

            $(".test").each(function(){
                var i = $('.test').index($(this));
                console.log(i);
            });
            

            jsFiddle example

            根据.index() 上的文档:

            如果在元素集合和 DOM 元素上调用 .index() 或 传入 jQuery 对象,.index() 返回一个整数,表示 传递的元素相对于原​​始集合的位置。

            【讨论】:

              猜你喜欢
              • 2021-05-30
              • 2020-03-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多