当单击“下一个/上一个”链接时,我的滑块允许内容前进和后退。当我将contentType切换为“ div”时,它仅显示幻灯片1和3中的内容。请问有人解释为什么计数器不能正确递增吗?有更有效的方法吗?我在下面包括了我的代码以及一个有效的示例。该脚本的目的是允许在幻灯片中显示图像或内容。任何帮助深表感谢!
$(document).ready(function() {
// VARIABLE DECLARATIONS
var $el = $('#showcase');
var $leftArrow = $('#left_arrow');
var $rightArrow = $('#right_arrow');
var contentType = $('div'); // change to img and reverse comment out HTML code
var slideCount = $el.children().length;
var slideNum = 1;
var $load = $el.find(contentType)[0];
// PRELOADS SLIDE WITH CORRECT SETTINGS
$load.className = 'active';
$leftArrow.addClass("disabled");
// CHECKS FOR FIRST AND LAST INDEX
function checkSlide() {
if (slideNum == 1) {
$leftArrow.addClass('disabled');
} else {
$leftArrow.removeClass('disabled');
}
if (slideNum == slideCount) {
$rightArrow.addClass('disabled');
} else {
$rightArrow.removeClass('disabled');
}
}
// NAVIGATIONAL LOGIC FOR PREVIOUS/NEXT BUTTONS
$leftArrow.click(function() {
if (slideNum > 1) {
var counter = $(".active").index();
counter--;
$('.active').addClass('slide');
$('.active').removeClass('active');
contentType.eq(counter).addClass('active');
slideNum--;
checkSlide();
console.log('slideNum: ' + slideNum);
console.log('counter: ' + counter);
}
})
$rightArrow.click(function() {
if (slideNum < slideCount) {
var counter = $(".active").index();
counter++;
$('.active').addClass('slide');
$(".active").removeClass('active');
contentType.eq(counter).addClass('active');
slideNum++;
checkSlide();
console.log('slideNum: ' + slideNum);
console.log('counter: ' + counter);
}
})
});
img {
width: 160px;
}
a {
color: blue;
}
.disabled {
color: red !important;
}
.slide {
display: none;
}
.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- <div id="showcase">
<img class="slide" src="https://picsum.photos/458/354" />
<img class="slide" src="https://picsum.photos/458/354/?image=306" />
<img class="slide" src="https://picsum.photos/458/354/?image=626" />
</div>
<a href="#" id="left_arrow">« Previous</a>
<a href="#" id="right_arrow">Next »</a> -->
<div id="showcase">
<div class="slide">Page 1 content</div>
<div class="slide">Page 2 content</div>
<div class="slide">Page 3 content</div>
</div>
<a href="#" id="left_arrow">« Previous</a>
<a href="#" id="right_arrow">Next »</a>
答案 0 :(得分:0)
问题在于,与div匹配的“ contentType” var也与“ showcase” div匹配,因此您的列表中得到4,而不是您期望的3。在左/右箭头单击处理程序中,替换为:
contentType.eq(counter).addClass('active');
具有:
$el.find(contentType).eq(counter).addClass('active');