使用 JS 随机化表行,同时一次显示一个表行

Randomize table rows with JS while displaying one table row at a time

本文关键字:一个 一次 显示 JS 随机化 使用      更新时间:2023-09-26

我正在尝试创建一个一次只显示一行的表,并且在每次刷新时也会随机化。这是我的代码:

<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>

这两个部分本身都可以正常工作,但是当我尝试组合它们时,随机化函数取代了其他代码,并且我得到了一长串刷新后随机化的tr。

我知道我可以做一些事情来使这些代码彼此一致。

有什么建议吗?

将整个第一块代码放入一个函数中:

function showOneRow() {
    ...
}

并在随机化后调用它:

window.onload = function() {
    randomize("song-list");
    showOneRow();
}