我有一个HTML表,每个单元格的值都为“Off”。当用户单击某个单元格时,我想将该单元格的值更改为“打开”,如果用户单击另一个单元格,则将其更改为“打开”,将先前更改的单元格恢复为“关闭”。 IE浏览器。只有一个单元格显示为“开”,所有其他单元格显示为“关闭”。这必须仅使用JavaScript和JQuery(非angularJS)
来完成<table id="switchboard-container">
<tbody>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
</tbody>
</table>
以下是我的尝试:
<script type="text/javascript">
$('#switchboard-container td').click(function ()
{
setClickHandlers();
});
function setClickHandlers() {
// Click handlers that change the content of switches to 'On' or 'Off'.
var cells = document.querySelectorAll('# switchboard -container td');
Array.prototype.forEach.call(cells, function (td) {
td.addEventListener('click', changeCell);
});
}
function changeCell() {
if (this.textContent == "On")
{
this.textContent == "Off";
}
else
{
this.textContent = "On";
}
}
</script>
我可以更改为“开启”,但我不知道如何将其他单元格设置为“关闭”。有人可以帮忙吗?
答案 0 :(得分:1)
您可以使用简单的点击处理程序来执行此操作
$('#switchboard-container td.switch').click(function() {
var $this = $(this);
if ($this.hasClass('on')) { //if the current element is on then we can just make it off
$this.text('Off');
} else {
$this.text('On'); //make the current td on
$('#switchboard-container td.switch.on').removeClass('on').text('Off'); //make other td which are on as off
}
$this.toggleClass('on');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="switchboard-container">
<tbody>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
</tbody>
</table>
答案 1 :(得分:1)
看看这个小提琴: https://jsfiddle.net/3fh4mLba/1/
基本上,添加$(".switch").text("Off");
会将文字设置为&#34;关闭&#34;在将它们更改为开启之前,所有这些都已完成。