获取元素的特定索引

时间:2016-09-26 20:04:25

标签: javascript jquery

我有以下代码:

<div class="something">
  <p class="same"> blah </p> <!-- should return index 0 -->
</div>

<div class="something-else">
  <p class="same"> blah </p> <!-- should return index 1 -->
</div>

<div class="other" >
  <p class="same"> blah </p> <!-- should return index 2 -->
</div>

我的问题很简单。当父母不同时,如何获得每个paragphs的索引?我试过这样的事情:

$('.same').each(function() { console.log( $(this).index() });

但是,显然它为每个元素返回了相同的值。

6 个答案:

答案 0 :(得分:2)

$('.same').each(function(index) { console.log( index });

答案 1 :(得分:2)

each函数附带一个索引参数。

$(".same").each(function(i) {
   console.log("index " + i); 
});

完整代码段

&#13;
&#13;
$(".same").each(function(i) {
   console.log("Item " + i);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<div class="something">
  <p class="same"> blah </p> <!-- should return index 0 -->
</div>

<div class="something-else">
  <p class="same"> blah </p> <!-- should return index 1 -->
</div>

<div class="other" >
  <p class="same"> blah </p> <!-- should return index 2 -->
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以将同一个类用作.index()

的选择器
$('.same').each(function() { 
    console.log( $(this).index('.same') );
});

当然,无论如何都会返回与each迭代相同的索引,但这就是基于使用index()的集合返回索引的方式,而不仅仅是基于元素的索引。父元素

来自文档

  

.index(选择器)

     

表示要在其中查找的jQuery集合的选择器   元件。

另一种方式也有效

$('.same').index(this)

答案 3 :(得分:0)

你真的很亲密。在函数内部,它保存当前元素的上下文与类相同。您想将它与具有“相同”类的整个元素列表进行比较,所以

$('.same').each(function() { console.log($('.same').index(this)))

答案 4 :(得分:0)

.index()返回其父级中的索引。由于这些段落中的每一段都是其中包含<div>的第一个元素,因此每次都会获得0。相反,您可以获得父级的索引:

&#13;
&#13;
$('.same').each(function() {
  console.log($(this).parent().index())
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="something">
    <p class="same">blah</p>
    <!-- should return index 0 -->
  </div>

  <div class="something-else">
    <p class="same">blah</p>
    <!-- should return index 1 -->
  </div>

  <div class="other">
    <p class="same">blah</p>
    <!-- should return index 2 -->
  </div>
</div>
&#13;
&#13;
&#13;

答案 5 :(得分:0)

这将有效:

$('.same').each(function(index) {console.log( index)});