我试图做到这一点,当您单击 <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/