0
如果我写了一个简单的选择像获取jQuery的元素的索引号点击
$('.button')
当它被点击,我可以计算出该按钮的“索引”?即第一次出现.button
,第二次,第三次?
我知道我可以选择与$('.button')[2]
第三个按钮,但我不知道如何获得这2值。
按钮遍布整个页面,而不是全部在同一个div内。
如果我写了一个简单的选择像获取jQuery的元素的索引号点击
$('.button')
当它被点击,我可以计算出该按钮的“索引”?即第一次出现.button
,第二次,第三次?
我知道我可以选择与$('.button')[2]
第三个按钮,但我不知道如何获得这2值。
按钮遍布整个页面,而不是全部在同一个div内。
可以调用index()
方法来做到这一点:
$('.button').click(function() {
var index = $(this).index();
console.log(index);
});
上述会给你在同级间的元素的索引。如果你想获得一组中的元素的索引,例如,如果.button
元素页面各处蔓延,没有兄弟姐妹,那么你可以到index()
提供一个选择器中的电流匹配元素:
$('.button').click(function() {
var index = $(this).index('.button');
console.log(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent"><button class="button">click me!</button></div>
<div class="parent"><button class="button">click me!</button></div>
<div class="parent"><button class="button">click me!</button></div>
<div class="parent"><button class="button">click me!</button></div>
<div class="parent"><button class="button">click me!</button></div>
完美,谢谢! – chendriksen
我想你可以使用.index() –