[英]How to get index, position number of element with certain class with jQuery
我有這個標記
<div class="parent">
<div class="one"></div>
<div class="two"></div>
<div class="one"></div>
<div class="two"></div>
</div>
我的問題是:如何獲得元素的“指數”號帶班two
。 我不問parent
div中元素的常規索引號。 我需要知道,當我在點擊帶班第一個元素one
,明年two
元有0指數或它的第一個元素在此列表與類two
,依此類推。
我已經嘗試過使用index()
方法和eq()
並且總是在parent
div中具有該元素的實際索引號。 我希望這很清楚,希望有所幫助。
您需要在具有相同類的元素集合中找到元素索引:
$('.parent > div').click(function(){
var index;
if($(this).is('.one'))
index = $('.parent > .one').index(this);
else
index = $('.parent > .two').index(this);
});
這應該是獲取所需索引的更快方法。
它不會檢索所有匹配項,而只是計算DOM中先前葉子之間相同類的元素數。
另外,它允許有多個<div class="parent">
並且仍然可以工作
$('.parent div').click(function() {
// Retrieve clicked element class (one, two)
var elClass = $(this).attr('class');
// Retrieve all previous elements that have the same class
// and count them
var prevElmts = $(this).prevAll('.' + elClass),
numPrevElements = prevElmts.length;
console.log(numPrevElements);
})
使用jQuery,您可以找到具有相同類名或標簽名的元素的索引
$(".class_name").on("event_name", function() {
var index=($(this).index());
console.log('index : ',index);
});
這可能對您有用。
var p = $('.parent'),
current = p.filter('.two'),
index = p.index(current);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.