获取DOM中所有匹配元素的当前元素的索引 [英] Getting the index of a current element across all matched elements in the DOM

查看:293
本文介绍了获取DOM中所有匹配元素的当前元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的DOM结构如下所示:

I have a DOM structure that looks like this:

<div class="chapter">
   <section></section>
   <section></section>
</div>
<div class="chapter">
   <section></section>
   <section></section>
   <section class="current"></section>
   <section></section>
</div>
<div class="chapter">
   <section></section>
   <section></section>
   <section></section>
   <section></section>
</div>

我希望获得所有部分中具有当前类的部分的索引号。在这个例子中,索引是5,因为它是第5节标记并包含一个当前类。

I want to get the index number of the section with a class of "current", across all sections. In this example the index of that would be 5, since it's the 5th section tag and contains a class of current.

如何使用jQuery获取此内容?

How do I get this with jQuery?

我从这开始就得到了dom中所有部分的列表:

I've started with this to get a list of all sections in the dom:

var sections = $('section');

我尝试过这样的事情来尝试获得我想要的结果:

I've tried things like this to try and get the result I want:

alert($(sections+'.current').index());

返回js错误。

我在这里想念的是什么?谢谢!

What am I missing here? Thanks!

推荐答案

在您的代码 $('section')中将所有部分作为jquery对象返回。其中要获取一个类当前的部分的索引,你可以这样做:

In your code $('section') would return you all the sections as a jquery object. Amongst them to get the index of a section which has a class of current you could do this:

sections.index($(".current"));

这会返回一个类为current的节的相对索引,该值为4,为
$('sections')会返回一个jQuery对象Array(0 indexed),其中包含所有section元素。所以匹配的元素是第5个元素,索引将返回4.
希望这个小提琴帮助。

This would return you a relative index of the section with class current, which would be 4 as $('sections') would return you a jQuery object Array(0 indexed) which contains all the sections elements. So the element which matches is the 5th element and index would return 4. Hope this fiddle helps.

这篇关于获取DOM中所有匹配元素的当前元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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