我正在尝试创建一个表,一次只显示一行,并在每次刷新时随机化。这是我的代码:
<script>
var maxRows = 1; //displays one row at a time
$('#song-list').each(function() {
var cTable = $(this);
var cRows = cTable.find('tr:gt(0)');
var cRowCount = cRows.size();
if (cRowCount < maxRows) {
return;
}
/* hide all rows above the max initially */
cRows.filter(':gt(' + (maxRows - 1) + ')').hide();
var cPrev = cTable.siblings('.prev');
var cNext = cTable.siblings('.next');
/* start with previous disabled */
cPrev.addClass('disabled');
cPrev.click(function() {
var cFirstVisible = cRows.index(cRows.filter(':visible'));
if (cPrev.hasClass('disabled')) {
return false;
}
cRows.hide();
if (cFirstVisible - maxRows - 1 > 0) {
cRows.filter(':lt(' + cFirstVisible + '):gt(' + (cFirstVisible - maxRows - 1) + ')').show();
} else {
cRows.filter(':lt(' + cFirstVisible + ')').show();
}
if (cFirstVisible - maxRows <= 0) {
cPrev.addClass('disabled');
}
cNext.removeClass('disabled');
return false;
});
cNext.click(function() {
var cFirstVisible = cRows.index(cRows.filter(':visible'));
if (cNext.hasClass('disabled')) {
return false;
}
cRows.hide();
cRows.filter(':lt(' + (cFirstVisible +2 * maxRows) + '):gt(' + (cFirstVisible + maxRows - 1) + ')').show();
if (cFirstVisible + 2 * maxRows >= cRows.size()) {
cNext.addClass('disabled');
}
cPrev.removeClass('disabled');
return false;
});
});
</script>
第二段代码:
<script>
Array.prototype.shuffle = function() {
for (var i = 0; i < this.length; i++) {
// Random item in this array.
var r = parseInt(Math.random() * this.length);
var obj = this[r];
// Swap.
this[r] = this[i];
this[i] = obj;
}
}
function randomize(tableID) {
var myTable = document.getElementById(tableID);
var myRows = new Array();
for (i=myTable.rows.length-1; i>=0; i--) {
var theRow = myTable.rows[i];
myRows.push(theRow);
theRow.parentNode.removeChild(theRow);
}
myRows.shuffle();
for (j=0; j<myRows.length; j++) {
myTable.appendChild(myRows[j]);
}
}
window.onload = function() {
randomize("song-list");
}
//-->
</script>
这两个部分都可以自行运行,但是当我尝试将它们组合起来时,randomize函数会取代其他代码,并且我得到一个很长的tr列表,它在刷新后随机化。
我知道我可以做些什么来使这些代码彼此一致。
有任何建议吗?
答案 0 :(得分:1)
将整个第一段代码放入函数中:
function showOneRow() {
...
}
并在随机化后调用它:
window.onload = function() {
randomize("song-list");
showOneRow();
}