显示所选单元格的数量

时间:2019-02-25 11:12:25

标签: javascript

我有以下代码将点击的单元格变为绿色,但我试图在网页顶部的段落中添加“ 选定的绿色单元格数:”,并在其中添加选定的绿色单元格。我不知道。在单击“确认”按钮后,我还需要在网站(../coordinates.txt)上的文件中记录所有选定绿色单元格的x,y坐标。 任何帮助将不胜感激:-)

CSS

.green { background: green; color: white; }
.white { background: white; color: black; }

#cells-list { border: 1px solid black; }
td { padding: 10px; border: 1px solid black; }

HTML

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 3</title>
<link rel="stylesheet" type="text/css" href="Untitled_1.css"/>
</head>
<body>
<form id="form1" runat="server">
<asp:Button id="Button1" runat="server" Text="Confirm" />
</form>

<table id="cells-list">
<tr>
<td class="white">TEST1</td>
<td class="white">TEST2</td>
<td class="white">TEST3</td>
</tr>
</table>
<script type="text/javascript">
var cells = document.querySelectorAll("td");
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
this.className= this.className == "white" ? "green" : "white";
});
}
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您可以这样做:

var numberOfSelectedCellsElem = document.querySelector('#numberOfSelectedCells');
document.querySelectorAll('td').forEach(c => {
  c.addEventListener('click', function() {
    this.className = this.className == 'white' ? 'green' : 'white';
    numberOfSelectedCellsElem.innerHTML = document.querySelectorAll('.green').length;
  });
});
.green {
  background: green;
  color: white;
}

.white {
  background: white;
  color: black;
}

#cells-list {
  border: 1px solid black;
}

td {
  cursor: pointer;
  padding: 10px;
  border: 1px solid black;
}
<p>number of selected green cells: <span id="numberOfSelectedCells">0</span></p>

<form id="form1" runat="server">
  <asp:Button id="Button1" runat="server" Text="Confirm" />
</form>

<table id="cells-list">
  <tr>
    <td class="white">TEST1</td>
    <td class="white">TEST2</td>
    <td class="white">TEST3</td>
  </tr>
</table>