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

Get index of parent based on child in jQuery

本文关键字:元素 获取 索引 jQuery      更新时间:2023-09-26

目前,下面的代码返回一个具有类.one-third的可见父/兄弟div的数组,但我需要根据返回的数组找到单击的文章的位置。例如,post-1320的索引为0,post-1321返回1,post-1324返回2,等等。

.index('.'+unqiuePostClass[1])添加到代码末尾返回-1,因为它无法定位类。

<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/

使用.index()并传递其相对元素的选择器:

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

jsFiddle例子/strong>

您可以在:visible元素上使用.index(), class为.one-third

$('.post').click(function() {
	var index = $('.one-third:visible > .post').index(this);
	console.log(index);
});
.one-third {
    width:33.3333333333333%;
    float:left;
}
.post {
    background:red;
    margin:5px;
    padding:5px;
    cursor:pointer;
}
.clear {clear:both;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>