我在计算div中的图像数量时遇到问题。
例如1 / 4、2 / 4、3 / 4、4 / 4
这是我正在尝试找出的小代码
//count image
var currentNum = $(this).iniShow() + 1;
var count = $(this).closest('.slideshow').find('img:first').length;
var item = $(this).closest('.slideshow').attr('id');
$('.' + item ).html(currentNum + ' of ' + count);
到目前为止,这是我的html代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script>
</head>
<style>
.slideshow img { display: none; cursor: pointer; }
</style>
<script type="text/javascript">
jQuery(function($){
//previous slide
$('.slideshow .prev').click(function() {
prevSlide($(this).closest('.slideshow').find('.slides'));
});
//next slide
$('.slideshow .next, .slideshow img,').click(function() {
nextSlide($(this).closest('.slideshow').find('.slides'));
});
//initialize show
iniShow();
function iniShow() {
// show first slide with caption
$('.slideshow').each(function() {
showSlide($(this).find('.slides'));
});
}
// move previous slide
function prevSlide($slides) {
$slides.find('img:last').prependTo($slides);
showSlide($slides);
}
// move next slide
function nextSlide($slides) {
$slides.find('img:first').appendTo($slides);
showSlide($slides);
}
// show slide with caption
function showSlide($slides) {
var $nextSlide = $slides.find('img:first');
//hide (reset) all slides
$slides.find('img').hide();
//fade in next slide
$nextSlide.fadeIn(500);
//show caption
$('#caption').text($nextSlide[0].alt);
//count image
var currentNum = $(this).iniShow() + 1;
var count = $(this).closest('.slideshow').find('img').length;
$('#count').html(currentNum + ' of ' + count);
}
});
</script>
<body>
<div class="slideshow">
<div class="slides">
<img src="image/1a.jpg" width="500" height="500" alt="Caption 1 Image is ..." />
<img src="image/2a.jpg" width="500" height="500" alt="Caption 2 Image is ..." />
<img src="image/3a.jpg" width="500" height="500" alt="Caption 3 Image is ..." />
<img src="image/4a.jpg" width="500" height="500" alt="Caption 4 Image is ..." />
</div>
<p id="caption"></p> / <p id="count"></p>
<div class="controls">
<a class="prev" href="javascript:void(0);">Previous</a> -
<a class="next" href="javascript:void(0);">Next</a>
</div>
</div>
</body>
</html>
任何建议,将不胜感激。我也想知道我即将解决这个问题。谢谢。
最佳答案
您可以直接使用count作为选择器。 changes in jsfiddle
对于
var item = $(this).closest('.slideshow').attr('id');
$('.' + item ).html(currentNum + ' of ' + count);
我相信您想在ID为
count
的div中显示计数。对于id,您应该使用#而不是。(用于类selectopr)。 $('#count').html(currentNum + ' of ' + count);
修改后的代码:
var currentNum = $(this).iniShow() + 1;
var count = $(this).closest('.slideshow').find('img').length;
$('#count').html(currentNum + ' of ' + count);
关于jquery - 计数Div中的图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12846854/