【问题标题】:Creating a Word Find grid创建单词查找网格
【发布时间】:2026-01-06 03:05:02
【问题描述】:

我正在尝试创建一个在每个框中包含一个字母的网格(如 Word Find 拼图)。

我已经成功创建了一个网格,显示了确定的列数/行数,但是当我尝试在每个框中放置一个字母时,我在每个框中得到以下十次而不是单个字母:

[object
Object]

这里是 JavaScript:

$(function() {

var letters = [
    'rzeabppssgcddrvddydtjrkei', // 1
    'cezcqubhniittonieqerbiuvm', // 2
    'jqcjnasionsncvbsrwtabddsu', // 3
    'olselesitneagittrjanreinv', // 4
    'nqnaisdenmeibvurellsnrioc', // 5
    'ydnlevrnyeaidrwifkufmsuis', // 6
    'dcccjeeaogsemudbeemefaptn', // 7
    'evonsqpdepislsnudnurwjbpo', // 8
    'grytiunnafsexattmtclaimoi', // 9
    'pnqrhocbiieeinoitacilppat', // 10
];
var letter = [];


function splitRows(arr, arr2) {
    for (let i=0; i < arr.length; i++) {
        arr[i].split();
        for (let j=0; j < arr.length; j++) {
            arr2[j] = arr[i][j];
        }
    }        
} 

splitRows(letters, letter);

function* gen(arr) {
    for(i=0; i < arr.length; i++) {
        yield arr[i];
    }
}

function generateGrid(rows, cols, arr) {
    var grid = "<table>";
    for(row = 1; row <= rows; row++) {
        grid += "<tr>";
        for(col = 1; col <= cols; col++) {
            grid += "<td>";
            for(let i=0; i < arr.length; i++) {
                grid += gen(arr).next(); // not sure if the .next() generator works yet
            }
            grid += "</td>"; // 'letters' needs to input the next letter in letters each time it is called
        }
        grid += "</tr>";
    }
    return grid;
}

$("#tableContainer").append(generateGrid(26, 22, letter));

});

第一个函数旨在获取行并将它们拆分为单个字母(最终将行作为输入,但出于测试目的,我将它们放在一个数组中)

第二个函数是插入到 generateGrid() 函数中的生成器,用于在每次创建框时生成序列中的下一个字母。

【问题讨论】:

  • 为清楚起见:HTML 确实包含 id

标签: javascript html grid generator


【解决方案1】:

您应该先将字符串数据转换为矩阵,然后才能通过表格运行矩阵。

下面的 jQuery 插件清空表格,并根据数据将其替换为行和列。

注意:我还添加了标签名称验证,以防调用插件的元素不是&lt;table&gt; 元素。

var DEBUG_EXPERIMENTAL = false;

initializePlugins(); // Forward Declaration of jQuery plugins

let rawStringData = `
  rzeabppssgcddrvddydtjrkei
  cezcqubhniittonieqerbiuvm
  jqcjnasionsncvbsrwtabddsu
  olselesitneagittrjanreinv
  nqnaisdenmeibvurellsnrioc
  ydnlevrnyeaidrwifkufmsuis
  dcccjeeaogsemudbeemefaptn
  evonsqpdepislsnudnurwjbpo
  grytiunnafsexattmtclaimoi
  pnqrhocbiieeinoitacilppat
`;

$('.word-search').buildWordSearch(rawStringData, 'letter');
$('.letter').enableHighliting('highlight');

function initializePlugins() {
  (($) => {
    $.stringToMatrix = function(str) {
      return str.trim().split('\n').map(row => row.trim().split(''));
    };
    $.fn.buildWordSearch = function(stringData, cellClass) {
      this.throwErrorIfNotType('TABLE');
      return this.append($('<tbody>')
        .append($.stringToMatrix(stringData).map(row => {
          return $('<tr>').append(row.map(col => {
            return $('<td>').addClass(cellClass).text(col);
          }));
        })));
    };
    $.fn.throwErrorIfNotType = function(expectedTagName) {
      let actualTagName = this.prop('tagName');
      if (actualTagName !== expectedTagName) {
        throw Error(`Element '${actualTagName}' is not a '${expectedTagName}'!`);
      }
    };
    $.fn.getCell = function(x, y) {
      return this.find(`tr:nth-child(${y + 1}) td:nth-child(${x + 1})`);
    };
    $.fn.enableHighliting = function(cls) {
      return this.each(() => {
        this.on({
          mouseover: function() {
            let $table = $(this).closest('table');
            let $row = $(this).closest('tr');
            let rowIndex = $row.index();
            let colIndex = $(this).index();
            let rowCount = $table.find('tbody tr').length;
            let colCount = $row.find('td').length;

            // Hightlights diagonals.
            if (DEBUG_EXPERIMENTAL) {
              let limit = rowCount;
              let xNeg = colIndex - 1;
              let xPos = colIndex + 1;
              let yNeg = rowIndex - 1;
              let yPos = rowIndex + 1;
              while (limit > 0) {
                if (xNeg > -1 && yNeg > -1) {
                  $table.getCell(xNeg, yNeg).addClass(cls);
                }
                if (xPos < colCount && yNeg > -1) {
                  $table.getCell(xPos, yNeg).addClass(cls);
                }
                if (xNeg > -1 && yPos < rowCount) {
                  $table.getCell(xNeg, yPos).addClass(cls);
                }
                if (xPos < colCount && yPos < rowCount) {
                  $table.getCell(xPos, yPos).addClass(cls);
                }
                xNeg--;
                xPos++;
                yNeg--;
                yPos++;
                limit--;
              }
            }

            $row.addClass(cls);
            $table.find(`td:nth-child(${colIndex + 1})`).addClass(cls);
          },
          mouseout: function() {
            let $table = $(this).closest('table');
            let $row = $(this).closest('tr');
            let rowIndex = $row.index();
            let colIndex = $(this).index();
            let rowCount = $table.find('tbody tr').length;
            let colCount = $row.find('td').length;

            // Un-hightlights diagonals.
            if (DEBUG_EXPERIMENTAL) {
              let limit = rowCount;
              let xNeg = colIndex - 1;
              let xPos = colIndex + 1;
              let yNeg = rowIndex - 1;
              let yPos = rowIndex + 1;
              while (limit > 0) {
                if (xNeg > -1 && yNeg > -1) {
                  $table.getCell(xNeg, yNeg).removeClass(cls);
                }
                if (xPos < colCount && yNeg > -1) {
                  $table.getCell(xPos, yNeg).removeClass(cls);
                }
                if (xNeg > -1 && yPos < rowCount) {
                  $table.getCell(xNeg, yPos).removeClass(cls);
                }
                if (xPos < colCount && yPos < rowCount) {
                  $table.getCell(xPos, yPos).removeClass(cls);
                }
                xNeg--;
                xPos++;
                yNeg--;
                yPos++;
                limit--;
              }
            }

            $row.removeClass(cls);
            $table.find(`td:nth-child(${colIndex + 1})`).removeClass(cls);
          }
        });
      });
    };
  })(jQuery);
}
.word-search {
  border: 2px solid #000;
  border-collapse: collapse;
}

.word-search td {
  width: 1.25em;
  height: 1.25em;
  line-height: 1.25em;
  text-align: center;
}

.highlight {
  background: #FFD;
}

.letter.highlight:hover {
  background: #FF0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="word-search"></table>

【讨论】:

  • 这是一个很好的程序,但它并不能完全回答问题......
  • 我添加了突出显示作为天赋。逻辑由你决定。