我有一个看起来像这样的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>
Run Code Online (Sandbox Code Playgroud)
我希望在所有部分中获得具有"当前"类的部分的索引号.在这个例子中,索引将是5,因为它是第5节标记并包含一类当前.
我如何使用jQuery获得这个?
我开始用这个来获取dom中所有部分的列表:
var sections = $('section');
Run Code Online (Sandbox Code Playgroud)
我尝试过这样的事情来尝试获得我想要的结果:
alert($(sections+'.current').index());
Run Code Online (Sandbox Code Playgroud)
这会返回一个js错误.
我在这里错过了什么?谢谢!
Alo*_*ain 13
在您的代码中$('section'),您将所有部分作为jquery对象返回.在其中获取具有类的部分的索引current可以执行此操作:
sections.index($(".current"));
Run Code Online (Sandbox Code Playgroud)
这将返回一个带有类current的节的相对索引,$('sections')它将返回4,因为
它将返回一个包含所有节元素的jQuery对象Array(0 indexed).所以匹配的元素是第5个元素,索引将返回4.希望这个小提琴有帮助.
$('.current').index('section');
Run Code Online (Sandbox Code Playgroud)
查看文档index.
如果选择器字符串作为参数传递,则.index()返回一个整数,指示原始元素相对于选择器匹配的元素的位置.如果找不到该元素,.index()将返回-1.