jQuery的从数组中获取元素的索引位置按类别 [英] jQuery get index position of an element by class from an array

查看:219
本文介绍了jQuery的从数组中获取元素的索引位置按类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面上的多个音乐播放器和需要让他们的指数拉从目前球员的位置。问题是, currentPlayer 是不是一个孩子,所以使用 .find .filter 然后的.index 总是返回 0 的值,因为没有别的是在数组。

所以,我需要找到播放器中 .currentPlayer 的指数阵列。

HTML(非常简单):

 < UL>
    <立GT;
        <物品>
             < D​​IV CLASS =玩家>< / DIV>
        < /条>
    < /李>
    <立GT;
        <物品>
             < D​​IV CLASS =玩家currentPlayer>< / DIV>
        < /条>
    < /李>
    <立GT;
        <物品>
             < D​​IV CLASS =玩家>< / DIV>
        < /条>
    < /李>
< / UL>

JavaScript的:

  VAR球员= $('球员'),
    电流= player.filter('。currentPlayer'),
    指数= current.index();


解决方案

current.index()将搜索其为元素的父。所以自从电流是一个唯一的孩子,这是零。

您可以通过一个选择器的.index ;它会告诉jQuery来这里面你的元素进行搜索。

  VAR球员= $('球员'),
    电流= player.filter('。currentPlayer'),
    指数= current.index('玩家');

或者,你可以告诉jQuery来搜索特定元素的数组里面:

  VAR球员= $('球员'),
    电流= player.filter('。currentPlayer'),
    指数= player.index(电流);

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();

解决方案

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);

这篇关于jQuery的从数组中获取元素的索引位置按类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆