2015-10-13 79 views
0

当前下面的代码返回一个类.one-third的可见父/同级div的数组,但我需要根据返回的数组找到所点击项目的位置。例如,后1320将有一个索引0,后1321将返回1,后1324将返回2等在jQuery中获取基于子项的父项索引

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

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); 

}); 

RESULT

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

甲的jsfiddle哪个更好正在示威ES我的问题:http://jsfiddle.net/lustre/rtf5L0gv/5/

+0

如果您点击与类的文章'.post'您确定_unique_后类点击文章,然后你选择与此_unique_类的所有文章 - 这将产生完全点击文章。为什么要绕道? – Andreas

回答

0

您可以在:visible元素使用.index()带班的.one-third

$('.post').click(function() { 
 
\t var index = $('.one-third:visible > .post').index(this); 
 
\t 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>