0

目前这个脚本从列表中获取单词并生成一个网格,每次给单词随机位置。生成单词后,我希望将它们拆分为单独的字符,彼此相邻的单元格,这样单词仍然有意义-我该怎么做?

  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');
4

1 回答 1

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);

http://jsfiddle.net/YJjkB/1/

于 2012-07-13T11:11:52.070 回答