我想创建一个带缩略图的简单产品滑块。虽然可能有超过3个缩略图,但我只想显示其中的3个。通过点击“更多”按钮,我打算隐藏已经可见的第一张图片,并通过更改它们的类别从隐藏的图片中显示其中一张。
代码工作得很好,直到hiddenImages[0]这里出了问题。Firefox控制台会给出以下错误:“TypeError: hiddenImages[0]未定义”
我做错了什么?
// All images
var images = $('[data-image]');
// Click for more images
var more = $('.more');
// Add show class to all images
images.each(function(index, element){$(this).parent().addClass('visible')})
// Hide images begining from 4th image
images.each(function(index, element){if($(this).data('image') >= 4)
{$(this).parent().removeClass('visible').addClass('hidden')} })
// Show big image when clicking thumbnail
images.each( function(index, element){
$(this).click(function(){ $('#pic img').attr('src', $(this).attr('src')) }) })
// Hide 1st from visible images and show first from hidden images
more.on('click', function(){
// Find all hidden images and remove visible class from first one
hiddenImages = images.hasClass('hidden');
hiddenImages[0].removeClass('visible').addClass('hidden');
})
#pic {
width: 300px;
height: 300px;
border: 1px solid #ccc;
margin-right: 5px;
float: left;
}
.thumbnails {
height: 300px;
width: 50px;
padding:0;
margin:0;
margin-right: 10px;
float: left;
}
.thumbnails li {
display: inline;
list-style: none;
float: left;
width: 70px;
height: 70px;
margin-bottom: 5px;
border:1px solid #ccc;
text-align: center;
}
.thumbnails li img {
width: 70px;
height: 70px;
cursor: pointer;
}
.more {
display: inline;
list-style: none;
float: left;
width: 70px;
height: 70px;
margin-bottom: 5px;
border:1px solid #ccc;
text-align: center;
}
.hidden {display: none!important;}
.visible {display: block!important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
<div id="pic">
<img src="https://placeimg.com/300/300/nature">
</div>
<ul class="thumbnails">
<li><img data-image="1" src="https://placeimg.com/300/300/nature"></li>
<li><img data-image="2" src="https://placeimg.com/300/300/any"></li>
<li><img data-image="3" src="https://placeimg.com/300/300/animals"></li>
<li><img data-image="4" src="https://placeimg.com/300/300/sepia"></li>
<li><img data-image="5" src="https://placeimg.com/300/300/grayscale"></li>
<li><img data-image="6" src="https://placeimg.com/300/300/tech"></li>
<li class="more">MORE</li>
</ul>
</div>
.get(0)
而不是[0]
。 如果您仍然想要jQuery包装的元素,请使用.first()
。 - mhodges.hasClass()
返回一个布尔值。 - mhodges