在jQuery中获取基于子项的父项索引

在jQuery中获取基于子项的父项索引

本文介绍了在jQuery中获取基于子项的父项索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,下面的代码返回一个可见的父类/同级div数组,其类为.one-third,但是我需要根据返回的数组找到被点击文章的位置.例如,后1320的索引为0,后1321的索引为1,后1324的索引为2,依此类推.

Currently the code below returns an array of visible parent/sibling div's with the class .one-third, but I need to find the position of the clicked article based on the returned array. For example, post-1320 would have an index of 0, post-1321 would return 1, post-1324 would return 2 etc.

在代码末尾添加.index('.'+unqiuePostClass[1])会返回-1,因为它无法找到该类.

Adding .index('.'+unqiuePostClass[1]) to the end of the code returns -1 because it can't locate the class.

HTML

<div class="one-third">
    <article class="post post-1320">post-1320</article>
</div>
<div class="one-third">
    <article class="post post-1321">post-1321</article>
</div>
<div class="one-third" style="display:none;">
    <article class="post post-1322">post-1322</article>
</div>
<div class="one-third" style="display:none;">
    <article class="post post-1323">post-1323</article>
</div>
<div class="one-third">
    <article class="post post-1324">post-1324</article>
</div>
<div class="one-third">
    <article class="post post-1325">post-1325</article>
</div>
<div class="one-third">
    <article class="post post-1326">post-1326</article>
</div>

<div class="clear"></div>

JQuery

$('.post').click(function() {
    var str = $(this).attr('class');
    var unqiuePostClass = str.split(" "); // unqiuePostClass[1] returns post-xxxx
    var result = $('.'+unqiuePostClass[1]).parent().siblings('.one-third:visible').addBack();

    console.log(result);

});

结果

0: div.one-third
1: div.one-third
2: div.one-third
3: div.one-third
4: div.one-third

一个JSFiddle可以更好地演示我的问题: http://jsfiddle.net/lustre/rtf5L0gv/5 /

A JSFiddle which better demonstrates my problem: http://jsfiddle.net/lustre/rtf5L0gv/5/

推荐答案

使用 .index() 并传入与之相关的元素的选择器:

Use .index() and pass in the selector of the elements it's relative to:

$(this).parent().index('div.one-third:visible')

jsFiddle示例

jsFiddle example

这篇关于在jQuery中获取基于子项的父项索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:45