2011-10-11 140 views
6

我有一个DOM结构,看起来像这样:获取当前元素的所有匹配的元素索引在DOM

<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部分的标签并且包含一个当前类。

我该如何使用jQuery获取?

我已经开始用它来获取DOM中的所有部分的列表:

var sections = $('section'); 

我已经试过这样的事情,试图得到我想要的结果:

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

返回一个js错误。

我在这里错过了什么?谢谢!

回答

11

在您的代码$('section')会返回所有部分作为jQuery对象。他们当中获得其中有一类current你可以做这部分的指标:

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

这将返回你带班电流部分的相对指标,这将是4作为 $('sections')将返回你一个jQuery对象数组(0索引),其中包含所有节的元素。所以匹配的元素是第5个元素,索引将返回4. 希望这fiddle帮助。

+0

这似乎应该工作,事实上,我在这里测试它http://jsfiddle.net/uae2U/它,但不幸的是在我的代码中它返回-1。这让我更接近,所以谢谢! – Cory

+0

如果它返回-1,那么在选择器中可能有一些错误。如果没有匹配,index()将返回-1。 –

0

改变这样

var sections = 'section'; 

你的代码是这样做的,它的错误

alert($($('section')+'.current').index()); 
+0

谢谢,但我没看到如何帮助。设置var sections ='section';除了创建一个文本字符串之外别无它法。 – Cory

+0

如果你应该像这样使用var sections = $('section'); 然后使用这个警报(sections.hasClass('current')。index()); –

6
$('.current').index('section'); 

参见index的文档。

如果选择器字符串作为参数传递,则.index()将返回一个整数,指示原始元素相对于选择器匹配的元素的位置。如果找不到元素,则.index()将返回-1。

+0

这个也可以。谢谢! – Cory

相关问题