1

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

<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 刷新后随机化的列表。

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

有什么建议吗?

4

1 回答 1

1

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

function showOneRow() {
    ...
}

并在随机化后调用它:

window.onload = function() {
    randomize("song-list");
    showOneRow();
}
于 2012-04-11T11:35:27.787 回答