实际上,您只需对现有代码进行 2 处小的更改:
- 首先 - 在两个 .click() 处理程序中禁用“循环”功能
- 第二 - 在 ctrlcontent() 函数中添加一个条件来显示/隐藏下一个/上一个链接
点击处理程序如下所示:
$('.wrapper .prev').click(function(e) {
e.preventDefault();
// Remove this line, since this causes the "cycle" effect
// ctrlcontent( i = !i ? all.length - 1 : --i );
// Use this logic:
// When we are on first tab then do nothing, since there is no previous tab
if (i == 0) {
// Do not call ctrlcontent, since there is no previous tab
} else {
i -= 1;
ctrlcontent(i);
}
});
$('.wrapper .next').click(function(e) {
e.preventDefault();
// Also remove this line and add the condition below:
//ctrlcontent( i = ++i % all.length );
// When we are on the last tab then do nothing, since there is no next tab
if (i == all.length-1) {
// Do nothing, since there is no next tab
} else {
i += 1;
ctrlcontent(i);
}
}).click();
ctrlcontent 函数需要几个条件来决定显示哪些链接:
function ctrlcontent(index_to_show) {
all.removeClass("active").addClass("passiv");
all.eq(index_to_show).removeClass("passiv").addClass("active");
// now check if we need to show/hide the prev/next links
if (index_to_show == 0) {
// We are on first page, so hide the "prev"-link
prev.hide();
}
if (index_to_show == all.length-1) {
// We are on the last tab, so hide the "next"-link
next.hide();
}
if (index_to_show > 0) {
// We are on a tab _after_ the first one, so there should be a "prev"-link
prev.show();
}
if (index_to_show < all.length-1) {
// We are a tab _before_ the last one, so we need the "next"-link
next.show();
}
}
注意:以上示例未进行优化。你可以把它们写得更短。
我的另一句话:您应该将变量“i”重命名为“current_tab”等。它使代码更易于阅读/调试。
这是较短版本中的相同代码:
$(".wrapper #tab1,.wrapper #tab2").tabs({active: 0}).tabs({
collapsible: false,
hide: {
effect: "slideUp",
duration: 20
},
show: {
effect: "slideDown",
duration: 200
}
});
var all = $('.wrapper .main').addClass("passiv");
var prev = $('.wrapper .prev');
var next = $('.wrapper .next');
var tab_count = all.length-1;
var i = -1; // I suggest to call this "current", etc. "i" is no good ides...
prev.click(function(e) {
e.preventDefault();
if (i != 0) {
i -= 1;
ctrlcontent(i);
}
});
next.click(function(e) {
e.preventDefault();
if (i < tab_count) {
i += 1;
ctrlcontent(i);
}
}).trigger('click');
function ctrlcontent(index_to_show) {
all.removeClass("active").addClass("passiv");
all.eq(index_to_show).removeClass("passiv").addClass("active");
if (index_to_show == 0) prev.hide();
if (index_to_show == tab_count) next.hide();
if (index_to_show > 0) prev.show();
if (index_to_show < tab_count) next.show();
}
$(function() {
$( ".wrapper .inner" ).buttonset();
});