這是一個工作例子,說明我會把它:http://jsbin.com/ogika
CSS:
.month.hide { display: none; }
HTML
<p><a href="#" class="month-next">Next Month</a></p>
<table class="month"><tr><td>a</td></tr></table>
<table class="month hide"><tr><td>b</td></tr></table>
<table class="month hide"><tr><td>c</td></tr></table>
<table class="month hide"><tr><td>d</td></tr></table>
JavaScript的:
$(function() {
$(".month-next").click(function() {
var months = $(".month"), numMonths = months.length, curr = 0;
return function() {
//Hide the current table, by adding the 'hide' class
months.eq(curr).addClass("hide");
//Get the index of next table in the list
curr = (curr + 1) % numMonths;
//Show the next table, by removing the 'hide' class
months.eq(curr).removeClass("hide");
}
}());
});
在上面的代碼,months
是表的列表...在這種情況下,保持4個元素;和numMonths
是元件的數量...即,4.
上述代碼的「魔力」是此行:將要顯示curr = (curr + 1) % numMonths;
即線獲取下一個元素的索引,並且它以循環方式工作。
讓我們舉個例子:
0 1 2 3
=========================
| a | b | c | d |
=========================
現在,讓我們說curr
是0:
0 1 2 3
=========================
| a | b | c | d |
=========================
^
//curr is currently 0
curr = (curr + 1) % numMonths; //(0 + 1) % 4
//now, curr is 1
0 1 2 3
=========================
| a | b | c | d |
=========================
^
該行的代碼被執行後,curr
變爲1:(0 + 1)%4 = 1.這意味着要顯示的元素的下一個索引是1。因此,我們得到下一個元素和表現出來,通過移除hide
類:months.eq(curr).removeClass("hide");
現在讓我們來看看其中curr
是最後一個元素的例子:3
0 1 2 3
=========================
| a | b | c | d |
=========================
^
//curr is currently 3
curr = (curr + 1) % numMonths; //(3 + 1) % 4
//now, curr is 0
0 1 2 3
=========================
| a | b | c | d |
=========================
^
正如你所看到的,curr
是現在0 ...因此循環繼續。
好吧,遠遠好於我的回答。流利得多。但是,當最後一個可見時,不會注意循環返回第一個項目:P – Jamiec 2010-02-25 13:06:19
可能需要在返回之前的末尾進行檢查:if($(「table」)。hasClass('month-show')) .length <1)$('table')。eq(0).addClass('month-show'); – 2010-02-25 13:15:16
@Jamiec ..因此沒有比你的回答更好:) – harpax 2010-02-25 18:36:23