jQuery get index position of an element by class f

2019-03-24 06:54发布

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.

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

HTML (very simplified):

<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:

var player  = $('.player'),
    current = player.filter('.currentPlayer'),
    index = current.index();

3条回答
放我归山
2楼-- · 2019-03-24 07:24

current.index() will search its parent for the element. so since current is an only child, it's zero.

You can pass a selector to .index; it'll tell jQuery to search inside that for your element.

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:

var player  = $('.player'),
    current = player.filter('.currentPlayer'),
    index = player.index(current);
查看更多
霸刀☆藐视天下
3楼-- · 2019-03-24 07:38

You're probably looking for

$('div.player').index($('.currentPlayer'))

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

查看更多
迷人小祖宗
4楼-- · 2019-03-24 07:45
var position = 0;
$('.player').each(function(i){
if ($(this).hasClass('currentPlayer') == true) { position = i; }
});
查看更多
登录 后发表回答