Day3 众里寻它千百度

  • Filter

在海量的数据中如果想要快速找到特定关键字的资料,我们需要filter这个很实用的功能,让我们可以将目光放在筛选後的结果做进一步分析。这里可以参考W3Schools的范例

  • Implement

首先我们在table.js中,将filter本体的功能拆成一个独立的function,其中输入的内容我们命名为filter此变数,而原本表格中的内容透过loop在指定的index栏位下去抓出每个cell的内容,便将此变数命名为txtValue,如范例中如果想要与大小写无关可在两个变数都加上toUpperCase()(或是toLowerCase())处理。然後再用indexOf看filter是否在txtValue里面,如果没有,则将这个row的display设为"none":

function filterTable(input, table, index) {
  // Declare variables
  let filter, tr, td, i, txtValue;
  filter = input.value;
  tr = table.getElementsByTagName("tr");
  // Loop through all table rows, and hide those who don't match the search query
  for (i = 1; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[index];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

接下来我们回到HTML中,在表格上方加入一个输入,属性中type设定为text,并增加placeholder为Search ...,这样就会有提示使用者要输入的用途,然後增加onkeyup属性为输入後执行的动作,我们会呼叫filterTable_data(),最後给个id叫filterInput_data,并用和表格同样div的设定包起来,这样对齐比较美观:

<div class="table-responsive px-2">
  <input type="text" id="filterInput_data" onkeyup="filterTable_data()" placeholder="Search ..." class="form-control"/>
</div>

接下来再回到table.js,做输入完成後的function,将输入的内容和对应的table给到filter本体的function:

function filterTable_data() {
  let input = document.getElementById("filterInput_data");
  let table = document.getElementById("dataTable");
  filterTable(input, table, 0);
}

我们可以测试一下,承续昨天的小班教学的成绩表,我们现在只要打上每个人的小名就会显示个人成绩:
https://ithelp.ithome.com.tw/upload/images/20210904/20141158wXwAMSs8Kb.jpg
至於如果我们想要让每个栏位都能做filter,这就是另一个(天)故事了...


<<:  懂很多的工程师最恐怖

>>:  Day4 第一个HTML网页制作

用资料结构看 evernote - 修改前 - DAY 10

前言 介绍完了资料结构的基本,就用来实际解决一下,自己在记事方面的结构调整。 今天会先整理出自己平常...

[Day 22] 针对API的单元测试(二)

我们昨天已经测试了一个Json的API, 那我们今天将测试方法改成这样 public functio...

Day 28 - Rotate String

大家好,我是毛毛。ヾ(´∀ ˋ)ノ 废话不多说开始今天的解题Day~ 796. Rotate Str...

Day15 - Ptt换页及新增文章列表项目

今天的内容算是当初一时没考虑到的东西。 主要是Ptt一页的文章最多列出20篇,若要搜寻到20篇以前的...

Day16 - 复习 Vue 生命周期

今天又跟大神学习 重新认识 Vue.js | Kuro Hsu 1-7 元件的生命周期与更新机制,(...