gpt4 book ai didi

javascript - 更改表中按钮的文本

转载 作者:行者123 更新时间:2023-11-28 15:55:11 25 4
gpt4 key购买 nike

我使用 javascript 编程的时间不长,并且有 Java 背景。我正在尝试在代码中使用事件处理程序,但遇到了问题。我有一个 3x3 的 table ,因为我正在制作 tic tac toe 游戏,当用户单击其中一个框时,我想将按钮文本更改为 X。所以我有我的表格的 html,按钮是表格数据和单击时我已将所有按钮分配给相同的功能。单击按钮时,我将其 ID 发送到我的函数,然后我尝试使用此 ID 参数来设置文本,但此时它没有发生,我有点困惑为什么不这样做。我还做了一个提示(paramID),paramID 是正确的,所以我不明白发生了什么。任何帮助将不胜感激!这可能是我做了一些愚蠢的事情。我尝试过 Firefox 和 Chrome...

这是我的代码:

<table id="tictable" border="1" 

<tr id="row1">
<td><button id="button1" type="button" onclick="actionPerformed(this.id)"</button></td>
<td><button id="button2" type="button" onclick="actionPerformed(this.id)"</button></td>
<td><button id="button3" type="button" onclick="actionPerformed(this.id)"</button></td>
</tr>


<tr >
<td><button id="button4" type="button" onclick="actionPerformed(this.id)"</button></td>
<td><button id="button5" type="button" onclick="actionPerformed(this.id)"</button></td>
<td><button id="button6" type="button" onclick="actionPerformed(this.id)"</button></td>
</tr>


<tr id="row3">
<td><button id="button7" type="button" onclick="actionPerformed(this.id)"</button></td>
<td><button id="button8" type="button" onclick="actionPerformed(this.id)"</button></td>
<td><button id="button9" type="button" onclick="actionPerformed(this.id)"</button></td>
</tr>

</table>

<script type="text/javascript">



function actionPerformed(paramID)
{

document.getElementById(paramID).value = "X";

}

</script>

最佳答案

您需要使用.innerHTML。

function actionPerformed(paramID)
{
document.getElementById(paramID).innerHTML = "X";
}

演示 here

最好的方法是删除所有内联 JavaScript 并使用它

window.onload = function () {
var all_buttons = document.querySelectorAll('button');
console.log(all_buttons);
for (i = 0; i < all_buttons.length; i++) {
all_buttons[i].addEventListener('click',function () {
this.innerHTML = 'X';
});
};
};

<强> Demo

关于javascript - 更改表中按钮的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19186818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com