<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loaded() {
var tbl = document.getElementById("tbl");
if(tbl != null) {
tbl.parentNode.removeChild(tbl);
}
var nrOfWordsToUse = Number(document.getElementById("howManyWords").value);
if(nrOfWordsToUse > 12 || nrOfWordsToUse < 0) {
alert("nrOfWordsToUse has to be between 0 and 12");
} else {
var initialListOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "aha", "beb", "pan", "pet", "pir", "pem"];
listOfWords = [];
for(var i = 0; i < nrOfWordsToUse; i++)
listOfWords[i] = initialListOfWords[i];
var positions = [];
for(var i = 0; i < 6; i++) {
positions[i] = ["", "", "", "", "", ""];
}
for(var i = 0; i < listOfWords.length; i++) {
var y = number0to5();
var x = number0or3();
if(positions[y][x] == "") {
positions[y][x] = listOfWords[i].charAt(0);
positions[y][x + 1] = listOfWords[i].charAt(1);
positions[y][x + 2] = listOfWords[i].charAt(2);
} else {
i--;
}
}
var table = document.createElement("table");
table.id = "tbl";
document.body.appendChild(table);
for(var i = 0; i < positions.length; i++) {
var row = table.insertRow(-1);
for(var j = 0; j < positions[i].length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = positions[i][j];
}
}
}
alert("end");
}
function number0to5() {
return Math.floor(Math.random() * 6);
}
function number0or3() {
return Math.random() > 0.5 ? 0 : 3;
}
</script>
</head>
<body>
<input id="howManyWords" value="6" /><input type="button" onclick="loaded()" value ="doIt"/>
</body>
</html>
这里是一个小提琴:http://jsfiddle.net/dpbzq/12/
关于您的要求,帮助你建立在我的代码到你:
我做了一个新的小提琴:http://jsfiddle.net/uv74h/2/
正如你所看到的,它是一个功能:rndSpaces。它需要1个参数;由3个字母组成的数组,最多12个字。他们不必预先洗牌;该功能将洗牌。该函数将尝试查找id为“myTable”的表格。如果它没有找到表格,它会创建一个表格并将其附加到id为“myDiv”的div(有一行注释掉;如果您想将其附加到正文,请取消注释该行并注释掉将表追加到div的行)。该函数清除表格中的所有内容,创建一个6x6网格并用单词填充它。我给了表格,行和单元格一个CSS样式(tablestyle,myRow和myCell)。
这是函数的例子获取调用:
rndSpaces(["pim", "pam", "pet", "rol", "fik", "fak", "ral"]);
来源
2012-07-27 13:50:30
Tom
烨不好意思忘记带他们出去@joeshmo – m0onio 2012-07-27 13:14:59
你总是想要的是6x6的? – 2012-07-27 13:15:57
@joeshmo是的,但它也需要很容易适应 – m0onio 2012-07-27 13:17:56