问题
I want to be able to hide/disable the prev link when I am at the first box and disable the next link at the last box because at the moment you can keep clicking on next at the last box and when you do this it breaks as clicking previous no longer works. see demo in fiddle
<span id="wrapper">
<span id="prev"><a href="#">Go to Prev</a></span>
<span id="content">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div id="start" class="box">6</div>
<div class="box">7</div>
</span>
<span id="next"><a href="#">Go to Next</a></span>
var $curr = $("#start");
$curr.css("display", "inline");
$("#prev a").click(function () {
$curr = $curr.prev();
$(".box").css("display", "");
$curr.css("display", "inline");
});
$("#next a").click(function () {
$curr = $curr.next();
$(".box").css("display", "");
$curr.css("display", "inline");
});
回答1:
I would do it this way:
http://jsfiddle.net/mBXYL/
var $curr = $("#start");
$curr.css("display", "inline");
$("#prev a").click(function() {
$curr = $curr.prev();
$(".box").css("display", "");
$curr.css("display", "inline");
$("#next").show();
if (!$curr.prev().length) {
$("#prev").hide();
}
});
$("#next a").click(function() {
$curr = $curr.next();
$(".box").css("display", "");
$curr.css("display", "inline");
$("#prev").show();
if (!$curr.next().length) {
$("#next").hide();
}
});
回答2:
EDIT to respect your project needs:
jsFiddle demo (hides buttons)
var currN = 5;
var boxN = $('#content .box').length;
$('#content .box').eq(currN).show();
function displayBox(){
pr= currN === 0 ? $('#prev').hide() : $('#prev').show() ;
nx= currN === boxN-1 ? $('#next').hide() : $('#next').show() ;
$('.box').eq(currN).show().siblings().hide();
}
$("#prev, #next").click(function () {
var whichBtn = this.id==='next' ? currN++ : currN--;
displayBox();
});
You dont need to disable your buttons, make a loop!
jsFiddle demo
var $curr = $("#start");
var currN = $curr.index();
var boxN = $('#content .box').length;
$curr.css("display", "inline");
function displayBox(){
if(currN === -1){
currN = boxN-1;
}else{
currN = currN % boxN;
}
$('.box').eq(currN).show().siblings().hide();
}
$("#prev a").click(function () {
currN--;
displayBox();
});
$("#next a").click(function () {
currN++;
displayBox();
});
I created here a simplified version (you don't need the
#start
) :
jsFiddle demo 2 (simplified)
THis is all you need:
var currN = 5; // set here start slide! (zero index based)
var boxN = $('#content .box').length;
$('#content .box').eq(currN).show();
function displayBox(){
var curBox = currN === -1 ? currN=boxN-1 : currN=currN%boxN;
$('.box').eq(currN).show().siblings().hide();
}
$("#prev, #next").click(function () {
var whichBtn = this.id==='next' ? currN++ : currN--
displayBox();
});
来源:https://stackoverflow.com/questions/11569846/disable-next-prev-at-the-start-end-of-the-list