我有一个问题。我试图在我的主页上进行随机棋盘布局(每次加载网站时,div都会切换位置)。这就是我提出的:
<head>
<script>
function shuffelSquares(squarenumber){
for(var j, x, i = squarenumber.length; i; j = Math.floor(Math.random() * i), x = squarenumber[--i], squarenumber[i] = squarenumber[j], squarenumber[j] = x);
return squarenumber;
}
</script>
</head>
<body>
<div class="background"></div>
<div class="chessBoard">
<div class="menu">
<li class="menu">PROJECTS</li>
<li class="menu">CONTACT</li>
</div>
<script>
var squareNumbers = ['1','2','3','4','5','6','7','8','9'];
squareNumbers = shuffelSquares(squareNumbers);
for(var i = 0; i<=squareNumbers.length-1; i++){
console.log(squareNumbers[i]);
div = document.createElement('div');
div.setAttribute('id', 'square'+squareNumbers[i]);
div.innerHTML = "<h1>" + squareNumbers[i] + "</h1>";
console.log(div);
}
</script>
<div id="square1"><h1>1</h1></div>
<div id="square2"><h1>2</h1></div>
<div id="square3"><h1>3</h1></div>
<div id="square4"><h1>4</h1></div>
<div id="square5"><h1>5</h1></div>
<div id="square6"><h1>6</h1></div>
<div id="square7"><h1>7</h1></div>
<div id="square8"><h1>8</h1></div>
<div id="square9"><h1>9</h1></div>
</div>
我想直接替换div。但是document.write()不是我理解的方式。
感谢您的回复。 :)
答案 0 :(得分:0)
您可以使用document.getElementById(squareId).innerHTML = // ...
以下是演示:http://jsfiddle.net/erCCX/
<div id="square1">1</div>
<div id="square2">2</div>
<div id="square3">3</div>
<div id="square4">4</div>
<button id="btn">click me</button>
document.getElementById('btn').onclick = function() {
for (var i = 1; i < 10; i++) {
document.getElementById("square" + i).innerHTML = "chess!";
}
};
答案 1 :(得分:0)
您可以尝试使用insertBefore
来获得结果,我创建了一个小型演示,只需重新加载几次以查看布局更改:http://jsfiddle.net/gSV7K/1/
var article = document.querySelector('article');
var elements = document.querySelectorAll('div');
for(var x=0; x < elements.length; x++){
var randomIndex = Math.floor(Math.random() * 9.99) + 1;
var randomElement = document.querySelector('div:nth-child(' + randomIndex + ')');
article.insertBefore(randomElement, elements[x]);
}