我需要在div中找到带有'active'类的img开始的下一个和上一个图像。问题是,搜索上一个和下一个图像总是返回0的长度,所以没有任何反应。
<style>
.container #left img{
display:hidden;
}
.container #left img.active{
display:block;
}
</style>
<div class="container">
<div id="left">
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.jpg" />
<img src="4.jpg" />
<img src="5.jpg" />
</div>
</div>
<div class="arrow-left"></div>
<div class="arrow-right"></div>
<script>
$('.container #left img:first-child').addClass('active');
$(document).off('click', '.arrow-left').on('click', '.arrow-left', function() {
var prev = $('.container #left img.active').closest('div').prev().find('img');
if (prev.length == 0) {
prev = $('.container #left img:last');
}
$('.container #left img').removeClass('active');
prev.addClass('active');
});
</script>
答案 0 :(得分:2)
正如我所评论的那样,您可以使用.next和.prev来查找紧随其后/之前的兄弟姐妹。由于<table style="width: 1000px;">
<tr>
<td>
<table style="width: 1000px;">
<tr>
<td style="width: 125px;">
<span style="font-size: 12px;">Table1_Col1Title</span>
</td>
<td style="width: 125px;">
<span style="font-size: 12px; ">Table1_Col2Title</span>
</td>
</tr>
<tr>
<td style="height: 15px;">
<span style="line-height: 100%; "> & Table1_Col1Details & </span>
</td>
<td style="height: 15px;">
<span style="line-height: 100%; "> & Table1_Col2Details & </span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table style="width:1000px;">
<tr>
<td style="width: 125px;">
<span style="font-size: 12px;">Table2_Col1Title</span>
</td>
<td style="width: 125px;">
<span style="font-size: 12px;">Table2_Col2Title</span>
</td>
</tr>
<tr>
<td style="height: 15px;">
<span style="line-height: 100%;"> & Table2_Col1Details & </span>
</td>
<td style="height: 15px;">
<span style="line-height: 100%;"> & Table2_Col2Details & </span>
</td>
</tr>
</table>
</td>
</tr>
</table>
应该是唯一的,因此此处不需要类id
。
因此您可以将选择器重写为:
.container
选择上一张图片。
您可以使用$('#left img.active').prev('img')
来重新使用左右逻辑,以决定用户是向左还是向右点击。
.is('arrow-left')
$('.container #left img:first-child').addClass('active');
$(document).off('click', '.arrow-left, .arrow-right').on('click', '.arrow-left, .arrow-right', function() {
var next;
var circler;
if ($(this).is('.arrow-left')) {
next = 'prev';
circler = ':last';
} else { // or if there would be more arrows, use : else if ($(this).is('.arrow-right'))
next = 'next';
circler = ':first';
}
// Use bracket notation to dynamically decide which function to call.
var nextTarget = $('#left img.active')[next]('img');
if (nextTarget.length == 0) {
nextTarget = $('#left img' + circler);
}
$('#left img').removeClass('active');
nextTarget.addClass('active');
});
#left img {
display: inline-block;
width: 20px;
height: 20px;
}
#left img.active {
background-color: cyan;
}
.arrow-left, .arrow-right {
display: inline-block;
width: 50px;
background-color: lightgray;
}