目前,此脚本从列表中获取单词并生成网格,每次都会给出单词随机位置。生成这些单词时,我希望将它们分成单个字符,放入彼此相邻的单元格中,这样这个单词仍然有意义 - 我该怎么做?
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "log", "pan", "can", "man", ];
var shuffledWords = listOfWords.slice(0, 12);
shuffledWords.sort(function () {
return 0.5 - Math.random();
});
var table = $('<table class="tablestyle">');
var rows = 6;
var cols = 2;
var tr;
var index;
for (var row = 0; row < rows; row++) {
tr = $('<tr>');
for (var col = 0; col < cols; col++) {
index = (row * cols) + col;
$('<td>').text(shuffledWords[index]).appendTo(tr);
}
tr.appendTo(table);
}
table.appendTo('body');
$('<table>' + innerTable + '</table>').appendTo('body');
答案 0 :(得分:1)
我是否正确地假设每个单词都需要一个新行,而单词中的字母则需要一个新单元格?
试试这个:
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "log", "pan", "can", "man", ];
var shuffledWords = listOfWords.slice(0, 12);
shuffledWords.sort(function () {
return 0.5 - Math.random();
});
var tbl = document.createElement('table');
tbl.style.border='solid 1px silver';
for (var i = 0; i < shuffledWords.length; i++)
{
var word = shuffledWords[i];
var row = document.createElement('tr');
for (var j = 0; j < word.length; j++)
{
var cell = document.createElement('td');
cell.style.border='solid 1px silver';
cell.innerText = word[j];
// IF FIREFOX USE cell.textContent = word[j]; INSTEAD
row.appendChild(cell);
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);