実際には、既存のコードに 2 つの小さな変更を加えるだけで済みます。
- まず、2 つの .click() ハンドラで「サイクル」機能を無効にします。
- 2 番目 - 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();
});