javascript - 如何更改 <td> 标签的内部值?

标签 javascript html html-table

我试图做到这一点,当您单击 <td> 之一时s 在表中,SVG 将出现在其中。 这是我的代码版本,有 4 个插槽而不是 64 个,但功能是相同的:

function addPiece() {
  document.getElementsByName("square").innerHTML = document.write("<svg width='100' height='100'> <circle cx='50' cy='50', r='40' stroke='black' stroke-width='4' fill='white' /> </svg>");
}
.square {
  background-color: #459f60;
  width: 100px;
  height: 100px;
}
<table style="border: 2px solid #808080">
  <tr>
    <td class="square" name="square" id="0-0" onclick="addPiece()"></td>
    <td class="square" name="square" id="0-1" onclick="addPiece()"></td>
  </tr>
  <tr>
    <td class="square" name="square" id="1-0" onclick="addPiece()"></td>
    <td class="square" name="square" id="1-1" onclick="addPiece()"></td>
  </tr>
</table>

这段代码的问题在于它只是用 SVG 替换了整个内容,而不是将其输入到 <td> 中。被点击了。 非常感谢在这里获得一些帮助,因为我在 js 和 html 方面的水平非常低。

最佳答案

问题出在使用document.write。这将覆盖您的整个文档 HTML。使用 .innerHTML 属性来覆盖所选元素内的 HTML。

请注意,在我的代码片段中,我添加了元素的 id,并将其传递给函数调用。

function addPiece(id) {
  document.getElementById(id).innerHTML = "<svg width='100' height='100'> <circle cx='50' cy='50', r='40' stroke='black' stroke-width='4' fill='white' /> </svg>"
}
.square {
  background-color: #459f60;
  width: 100px;
  height: 100px;
}
<table style="border: 2px solid #808080">
  <tr>
    <td class="square" id="square1" name="square" id="0-0" onclick="addPiece(this.id)"></td>
    <td class="square" id="square2" name="square" id="0-1" onclick="addPiece(this.id)"></td>
  </tr>
  <tr>
    <td class="square" id="square3" name="square" id="1-0" onclick="addPiece(this.id)"></td>
    <td class="square" id="square4" name="square" id="1-1" onclick="addPiece(this.id)"></td>
  </tr>
</table>

关于javascript - 如何更改 <td> 标签的内部值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59721901/

相关文章:

java - NoClassDefFoundError + Appl

html - 如何使用 CSS 将这些表格中的 3 个放到正确的位置

javascript - 如何评估数组中每个项目包含 settimeout 的函数 (Javascript)

javascript - knockout 可观察数组的可观察数组

javascript - Ajax 和就绪状态

css - 具有固定表格布局的表格单元格的宽度不起作用

html - 如何调整html表格中固定行的宽度

javascript - 在 JavaScript 中验证十进制数字 - IsNumeric()

javascript - 如何通过 Google Chart API 使用 csv 文件?

javascript - 获取链接照片并插入另一个 div?