随机改组innerHTML

时间:2014-05-14 18:33:26

标签: javascript html shuffle

我正在试图改变som innerHTML,我创建了一些分区,我是从列表中添加内容,现在我想在每次加载网站时将其洗牌。我已经提出了这个解决方案,并且它会改进innerHTML,但它并没有将它放在新的HTML中。任何想法如何调整它?稍后我将创建并随机播放图像图片的href列表。所以基本上它将是一个9平方的图像随机发生器。我真的会帮助一些帮助:)

<script>

var squareNumbers = ['1','2','3','4','5','6','7','8','9']; //need to create a new list to append image hrefs

        for(var i = 0; i<=squareNumbers.length-1; i++){ //creates the chessboard
            var div = document.createElement('div');
            div.setAttribute('id', 'square'+squareNumbers[i]);
            div.innerHTML = squareNumbers[i];
            var checkHTML = document.getElementById('chessBoard').appendChild(div);
        }

        window.onload = function(){
        var squareDivs = document.getElementById('chessBoard').getElementsByTagName('div');
        var array = [];

        for(var i = 0; i < squareDivs.length; i++){ //creates an array of the squares innerHTML
            array.push(squareDivs[i].innerHTML);    
        }

        var i = array.length, j, temp;
        while(--i > 0){ //shuffles the array according to Fisher Yeates algorithm
            j = Math.floor(Math.random() * (i+1));
            temp = array[j];
            array[j] = array[i];
            array[i] = temp;
            var squares = document.getElementById('chessBoard').getElementsByTagName('div').innerHTML = temp;
            console.log(squares);

        }

        }


        </script>

1 个答案:

答案 0 :(得分:0)

<强>更新

这只是更新它们。

var squareNumbers = ['1','2','3','4','5','6','7','8','9'], j, temp;

for(var i = 0; i < squareNumbers.length; i++){ //creates the chessboard
    var div = document.createElement('div');
    div.setAttribute('id', 'square' + squareNumbers[i]);
    div.innerHTML = squareNumbers[i];
    document.getElementById('chessBoard').appendChild(div);
}

window.onload = function(){

    for (i = squareNumbers.length - 1; i >= 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        temp = squareNumbers[j];
        squareNumbers[j] = squareNumbers[i];
        squareNumbers[i] = temp;
        document.getElementById('chessBoard').getElementsByTagName('div')[i].innerHTML = temp;
    }
}


上一页

在这里,这样做:

window.onload = function(){
    var squareNumbers = ['1','2','3','4','5','6','7','8','9'], j, temp;

    for (i = squareNumbers.length - 1; i >= 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        temp = squareNumbers[j];
        squareNumbers[j] = squareNumbers[i];
        squareNumbers[i] = temp;
        var div = document.createElement('div');
        div.setAttribute('id', 'square'+squareNumbers[i]);
        div.innerHTML = squareNumbers[i];
        document.getElementById('chessBoard').appendChild(div);
    }
}