我有一个表和一个输入,人们应该在其中输入 1-12 月份,提交时,该月的行应变为红色。如何从这些日期中获取月份以确定它们来自哪个月份?我不确定如何继续。
<input type="text" placeholder="Kuukausi" id="searchMonth"/>
<button type="submit" id="searchbutton">
<span>Etsi</span></button>
</div>
<table style="width: 100%" id="table">
<tr>
<th>Lintu</th>
<th>Päivä</th>
</tr>
<tr>
<td>Varis</td>
<td>20.4.2018</td>
</tr>
<tr>
<td>Huuhkaja</td>
<td>14.9.2018</td>
</tr>
<tr>
<td>Pääskynen</td>
<td>24.4.2018</td>
</tr>
<tr>
<td>Peippo</td>
<td>30.3.2018</td>
</tr>
最佳答案
- 使用
type="number"
输入元素 - 无需“提交”按钮。
- 向
tbody
添加 ID - 使用 JS TableElement
rows
和 TableRowElementcells
对象 - 使用
“input”
事件触发searchMonth()
函数 - 循环 TBODY TR 元素,找到第
1
索引单元格,并按.
点分割其内容以检索月份字符串。 - 检查分割的日期月份是否等于输入的月份
- 使用 JS
Element.classList.toggle('className', boolean)
切换 CSS.highlight
类
const tbody = document.querySelector("#tableTbody");
const searchMonth = evt => {
const monthValue = evt.target.value.trim();
[...tbody.rows].forEach(row => {
const month = row.cells[1].textContent.split('.')[1];
row.classList.toggle('highlight', monthValue == month);
})
};
document.querySelector("#searchMonth").addEventListener('input', searchMonth);
.highlight td {
background: yellow;
}
<label>Month: <input type="number" id="searchMonth" min=1 max=12></label>
<table>
<thead>
<tr>
<th>Foo</th>
<th>Date</th>
</tr>
</thead>
<tbody id="tableTbody">
<tr>
<td>a</td>
<td>20.4.2018</td>
</tr>
<tr>
<td>b</td>
<td>14.9.2018</td>
</tr>
<tr>
<td>c</td>
<td>24.4.2018</td>
</tr>
<tr>
<td>d</td>
<td>30.3.2018</td>
</tr>
</tbody>
</table>
关于javascript - 根据月份突出显示行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60245141/