首页 > 解决方案 > 如何动态设置 HTML带有百里香的名字

问题描述

我有一个从控制器接收二维数组的表单,并且我已经通过 thymeleaf 生成了表格。

<div class="col-4 offset-4">
  <form id="sudokuBoard" method="post" enctype="application/x-www-form-urlencoded" class="form-group text-center">
    <div class="container">
      <table class="row-eq-height table-striped table-bordered text-center">
        <!--/*@thymesVar id="board" type=""*/-->
        <tr th:each="row: ${board}">
          <td th:each="value: ${row}">
            <div th:switch="${value}" class="col-xs-4">
              <input name="cellValue" th:case="0" class="content form-control input" style="text-align:center" type="text" pattern="[0-9]*" maxlength="1" value="0" onkeypress="return isNumber(event)" oninput="moveMade()">
              <input name="cellValue" th:case="*" class="content form-control input" style="text-align:center;background-color:lightgreen" type="text" th:value="${value}" readonly>
            </div>
          </td>
        </tr>
      </table>
      <div class="gap-10"></div>
      <button type="submit" class="btn btn-outline-primary btn-sm">Check Solution</button>
      <button class="btn btn-outline-primary btn-sm" id="btnNewGame">New Game</button>
      <button class="btn btn-outline-primary btn-sm" id="solveBoard"> Solve Puzzle</button>
    </div>
  </form>
</div>

所有输入字段都具有相同的名称,我想通过 Thymeleaf 动态分配名称cellValueX,以便区分每个单元格以检查用户输入的移动的有效性。

标签: javascriptjavahtmlthymeleaf

解决方案


你使用属性th:name有关可以与 Thymeleaf 一起使用的属性列表,请参阅此内容。我从您的代码中具体不知道您想X在 in中使用什么cellValueX,但可能是这样的?

<tr th:each="row, y: ${board}">
    <td th:each="value, x: ${row}">
        <input th:name="|cellValue${x.index}_${y.index}|" ... />
    </td>
</tr>

推荐阅读