實現鍵盤數字0-9的隨機排列
html
<div id="content"> <button value="1">1</button> <button value="2">2</button> <button value="3">3</button> <button value="4">4</button> <button value="5">5</button> <button value="6">6</button> <button value="7">7</button> <button value="8">8</button> <button value="9">9</button> </div>
css
*{ margin:0; padding: 0; } #content{ width: 500px; height: 500px; margin: 100px auto 0; } button{ width: 30%; height: 30%; box-sizing: border-box; font-size: 18px; }
js
var buttons = document.getElementsByTagName("button");
function fn(n)
{
var array = new Array();
for(var i= 0; i<n; i++)
{
var rnd = Math.floor(Math.random()* (9) ) + 1;
if(isIncluded(rnd, array))
{
i--;
}
else
{
array.push(rnd);
}
}
return array;
}
function isIncluded(element, array)
{
for (var i = 0, len = array.length; i < len; i++)
{
if(array[i] == element)
{
return true;
}
}
return false;
}
demo = fn(9);
for(var i= 0; i<demo.length; i++)
{
buttons[i].innerHTML = demo[i];
console.log(buttons[i].innerHTML);
}