目前,下面的代码返回一个包含类.one-third
的可见父/兄弟div的数组,但我需要根据返回的数组找到所点击文章的位置。例如,1320之后的指数为0,1321之后将返回1,之后的1324将返回2等。
在代码末尾添加.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:http://livingston-new.dev/sample-post/
答案 0 :(得分:1)
答案 1 :(得分:0)
您可以.index()
元素使用:visible
,.one-third
$('.post').click(function() {
var index = $('.one-third:visible > .post').index(this);
console.log(index);
});
&#13;
.one-third {
width:33.3333333333333%;
float:left;
}
.post {
background:red;
margin:5px;
padding:5px;
cursor:pointer;
}
.clear {clear:both;}
&#13;
<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>
&#13;