2016-12-15 99 views
0

jQuery中获取使用索引()的元素的索引

$(document).ready(function() { 
 
    var box = $('.box'); 
 
    box.click(function() { 
 
    console.log($(this).index()); 
 
    }); 
 
});
div, section { 
 
    border: 1px solid red; 
 
    width: 80px; 
 
    height: 80px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="box">1</div> 
 
<div class="box">2</div> 
 
<div class="para">3</div> 
 
<div class="box">4</div>

在上述HTML,与.box类的最后一个div是第三.box,我想最后.box的索引是3 ,但我得到4。我应该使用哪个jQuery函数,它将搜索所有div类的box,然后在点击.box的位置返回我的位置.box

+0

索引返回被考虑到母体内的所有元素。如果你想过滤你可以为方法提供一个选择器或者在选择器上调用它。 [jQuery .index()](https://api.jquery.com/index/) – melancia

+0

http://api.jquery.com/index它的记录很好。 –

回答

3

可以使用.index()当你比较它一组元素与$('.box').index($(this))

如果选择字符串被作为参数传递,的.index()返回一个整数 指示第一元件的位置在相对于选择器匹配的元素的jQuery 对象内。

顺便说一句,.index()是从零开始的,所以索引应该是0,1和2.如果你想要1,2和3,只需要在结果中加1。

$(document).ready(function() { 
 
    var box = $('.box'); 
 
    box.click(function() { 
 
    console.log($('.box').index($(this))); 
 
    }); 
 
});
div, 
 
section { 
 
    border: 1px solid red; 
 
    width: 80px; 
 
    height: 80px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="box">1</div> 
 
<div class="box">2</div> 
 
<div class="para">3</div> 
 
<div class="box">4</div>