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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:39:04  来源:igfitidea点击:

jQuery get index position of an element by class from an array

jqueryarraysclassfilter

提问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 currentPlayeris not a child, so using .findor .filterand then .indexwill always return a value of 0because nothing else is in the array.

我在一个页面上有多个音乐播放器,需要制作它们的索引以从中拉出当前播放器的位置。问题是这currentPlayer不是一个孩子,所以使用.findor.filter和 then.index将始终返回一个值,0因为数组中没有其他东西。

So I need to find .currentPlayer's index within the playerarray.

所以我需要.currentPlayerplayer数组中找到的索引。

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 currentis 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'))

http://jsfiddle.net/hmartiro/3Wzbd/

http://jsfiddle.net/hmartiro/3Wzbd/

回答by Silviu Burcea

var position = 0;
$('.player').each(function(i){
if ($(this).hasClass('currentPlayer') == true) { position = i; }
});