jQuery jQuery从数组中按类获取元素的索引位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12413209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery get index position of an element by class from an array
提问by technopeasant
I've got multiple music players on a page and need to make an index of them to pull the position of the current player from. The issue is that the currentPlayer
is not a child, so using .find
or .filter
and then .index
will always return a value of 0
because nothing else is in the array.
我在一个页面上有多个音乐播放器,需要制作它们的索引以从中拉出当前播放器的位置。问题是这currentPlayer
不是一个孩子,所以使用.find
or.filter
和 then.index
将始终返回一个值,0
因为数组中没有其他东西。
So I need to find .currentPlayer
's index within the player
array.
所以我需要.currentPlayer
在player
数组中找到的索引。
HTML (very simplified):
HTML(非常简化):
<ul>
<li>
<article>
<div class="player"></div>
</article>
</li>
<li>
<article>
<div class="player currentPlayer"></div>
</article>
</li>
<li>
<article>
<div class="player"></div>
</article>
</li>
</ul>
JavaScript:
JavaScript:
var player = $('.player'),
current = player.filter('.currentPlayer'),
index = current.index();
回答by Rocket Hazmat
current.index()
will search its parent for the element. so since current
is an only child, it's zero.
current.index()
将在其父元素中搜索该元素。因为current
是独生子,所以为零。
You can pass a selector to .index
; it'll tell jQuery to search inside that for your element.
您可以将选择器传递给.index
; 它会告诉 jQuery 在里面搜索你的元素。
var player = $('.player'),
current = player.filter('.currentPlayer'),
index = current.index('.player');
Or, you can tell jQuery to search for a specific element inside of an array:
或者,您可以告诉 jQuery 在数组中搜索特定元素:
var player = $('.player'),
current = player.filter('.currentPlayer'),
index = player.index(current);
回答by hayk.mart
You're probably looking for
你可能正在寻找
$('div.player').index($('.currentPlayer'))
回答by Silviu Burcea
var position = 0;
$('.player').each(function(i){
if ($(this).hasClass('currentPlayer') == true) { position = i; }
});