javascript - 根据月份突出显示行

标签 javascript jquery

Table

我有一个表和一个输入,人们应该在其中输入 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 和 TableRowElement cells 对象
  • 使用“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/

相关文章:

javascript - 如何区分单击+拖动与双击+拖动

javascript - 在 div 中隐藏/显示 swf?

javascript - javascript中特色轮播 slider 的响应式设计

Javascript 和渲染暂停并在 Android 浏览器中滚动时保持暂停状态

javascript - 是否可以将 html 中的函数传递给 lit-element?

javascript - 使 JSON-RPC jQuery 插件与 GAE ProtoRPC 配合使用

JQuery 与 IE 读取继承的 css 属性,如何防止?

jquery - JQuery.parseJSON 的无效 JSon 错误

javascript - 点击元素方式的图片

javascript - 如何在 meteor 页面加载后调用函数