每次按下播放按钮时,我都想创建一个2x2按钮的"数组"(它看起来像一个数组,但实际上不是,它是由for循环创建的)。我使用for循环来打印行,在循环中,我使用var按钮和一个附加br的"if"来打印新行。虽然它似乎确实在for循环中打印了br,但当他完成for循环时,br就会消失(我用一个警告"bug"来显示这一点)
var table1=["1","2","3","4"];
function shuffle(array) {
var currentIndex = array.length, temporaryValue,randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function printButtons(table1){
shuffle(table1);
var buttons = 0;
var y,t;
var mybr = document.createElement('br');
var par = document.getElementById("div2");
document.body.appendChild(mybr);
for(var i =0 ; i<4; i++){
y = document.createElement("button");
t = document.createTextNode(table1[i]);
y.setAttribute("id",table1[i]);
y.appendChild(t);
document.body.appendChild(y);
buttons=buttons+1;
if(buttons== 2){
alert("bug");
buttons= 0 ;
document.body.appendChild(mybr);
}
}
document.body.appendChild(mybr);
}
</script>
<div id="div1">
<button type="button" onclick="printButtons(table1)">play</button>
<br>
</div>
<div id ="div2"></div>
</body>
当appendChild(mybr)
和mybr
已经在DOM中时,它将被移动到新位置。修复方法是每次需要插入一个新的<br/>
:
buttons = buttons + 1;
if (buttons == 2) {
buttons = 0;
document.body.appendChild(document.createElement('br'));
}