javascript - 如何隐藏所有内容,直到用户搜索此表中的特定元素?

标签 javascript jquery html css html-table

我想创建一个表格,其中包含对用户隐藏的内容,但如果他们键入特定元素,则可以使用该表格。所以,基本上,我只想将搜索栏作为唯一显示的内容。

这是我已经拥有的,来自 w3schools:

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    * {
      box-sizing: border-box;
    }
    
    #myInput {
      background-image: url('/css/searchicon.png');
      background-position: 10px 10px;
      background-repeat: no-repeat;
      width: 100%;
      font-size: 16px;
      padding: 12px 20px 12px 40px;
      border: 1px solid #ddd;
      margin-bottom: 12px;
    }
    
    #myTable {
      border-collapse: collapse;
      width: 100%;
      border: 1px solid #ddd;
      font-size: 18px;
    }
    
    #myTable th,
    #myTable td {
      text-align: left;
      padding: 12px;
    }
    
    #myTable tr {
      border-bottom: 1px solid #ddd;
    }
    
    #myTable tr.header,
    #myTable tr:hover {
      background-color: #f1f1f1;
    }
  </style>
</head>

<body>

  <h2>My Customers</h2>

  <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

  <table id="myTable">
    <tr class="header">
      <th style="width:60%;">Name</th>
      <th style="width:40%;">Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Berglunds snabbkop</td>
      <td>Sweden</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Koniglich Essen</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Italy</td>
    </tr>
    <tr>
      <td>North/South</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Paris specialites</td>
      <td>France</td>
    </tr>
  </table>

  <script>
    function myFunction() {
      var input, filter, table, tr, td, i, txtValue;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
          txtValue = td.textContent || td.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        }
      }
    }
  </script>

</body>

</html>

最后,我如何才能在元素上添加可点击的链接?我见过一个具有这些功能的网站,我试图自己找到答案,但找不到。我也是一个初学者,编码背景为零,尽管过去几周我学得很快。因此,如果您使用我能理解的词语,我将不胜感激。

如果你想知道我要做什么,我计划建立一个免费的图书博客,人们可以在其中搜索他们最喜欢的作者或书名,如果有的话,它会出现在搜索栏上。 多谢!

最佳答案

这是我的做法。我尝试添加尽可能多的评论来解释为什么我做了一些事情。 HTML、CSS 和 JS 代码中都有一些。有任何问题请随时提问。

// When the DOM (HTML structure) is ready
document.addEventListener("DOMContentLoaded", function() {
  // First, we can create references to DOM elements on page start,
  // which we'll reuse instead of looking them up every time we perform a search.
  // As a convention, I like variables holding DOM elements to start with $,
  // so that I know what I'm dealing with in the blink of an eye 👀
  var $input = document.getElementById("myInput"),
      $table = document.getElementById("myTable"),
      // Only select the <tr>s inside the <tbody> (double $ -> multiple elements)
      $$tr   = $table.querySelectorAll("tbody tr");

  // Add the normalized name as a property to each tr, so that you don't have
  // to compute that every time when performing a search
  for (var i = 0; i < $$tr.length; i++) {
    $$tr[i].normalizedValue = normalizeStr( $$tr[i].querySelector("td").innerText );
  }
  // When typing or pasting text, perform a search
  $input.addEventListener("input", performSearch);

  function performSearch() {
    var filter = normalizeStr(this.value);
    for (var i = 0; i < $$tr.length; i++) {
      var isMatch = $$tr[i].normalizedValue.includes(filter);
      // Toggle a 'visible' class
      $$tr[i].classList[isMatch ? "add" : "remove"]("visible");
    }
  }

  // Creating a reusable function will allow us to make
  // changes to it only in one place 👍
  function normalizeStr(str) {
    return str.toUpperCase().trim();
  }
});
/* ... untouched CSS ... */ *{box-sizing:border-box}#myInput{background-image:url(/css/searchicon.png);background-position:10px 10px;background-repeat:no-repeat;width:100%;font-size:16px;padding:12px 20px 12px 40px;border:1px solid #ddd;margin-bottom:12px}#myTable{border-collapse:collapse;width:100%;border:1px solid #ddd;font-size:18px}#myTable td,#myTable th{text-align:left;padding:12px}#myTable tr{border-bottom:1px solid #ddd}

#myTable thead tr, /* notice the use of thead */
#myTable tr:hover {
  background-color: #f1f1f1;
}

#myTable tbody tr {
  display: none; /* Hide rows by default */
}

#myTable tbody tr.visible {
  display: table-row; /* Show them when they match */
}
<h2>My Customers</h2>

<!-- Try not using `on...=""` attributes. Separating HTML and JS is better practice -->
<input type="text" id="myInput" placeholder="Search for names" title="Type in a name" />

<table id="myTable">
  <!-- Use <thead> and <tbody> to separate data from headers -->
  <thead>
    <tr>
      <th style="width:60%;">Name</th>
      <th style="width:40%;">Country</th>
    </tr>
  </thead>
  <tbody>
    <tr> <td><a href="http://example.com/">Alfreds Futterkiste</a></td> <td>Germany</td> </tr>
    <tr> <td><a href="http://example.com/">Berglunds snabbkop</a></td> <td>Sweden</td> </tr>
    <tr> <td><a href="http://example.com/">Island Trading</a></td> <td>UK</td> </tr>
    <tr> <td><a href="http://example.com/">Koniglich Essen</a></td> <td>Germany</td> </tr>
    <tr> <td><a href="http://example.com/">Laughing Bacchus Winecellars</a></td> <td>Canada</td> </tr>
    <tr> <td><a href="http://example.com/">Magazzini Alimentari Riuniti</a></td> <td>Italy</td> </tr>
    <tr> <td><a href="http://example.com/">North/South</a></td> <td>UK</td> </tr>
    <tr> <td><a href="http://example.com/">Paris specialites</a></td> <td>France</td> </tr>
  </tbody>
</table>

关于javascript - 如何隐藏所有内容,直到用户搜索此表中的特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60234096/

相关文章:

javascript - 复选框值的总和

javascript - pdf文件上传并存储在javascript中的文件夹中

javascript - 如何确定是否选择了复选框下拉菜单的不同部分?

JavaScript:覆盖 get 和 set 但保留 native 功能

同一行上的 jquery 显示/隐藏按钮显示不漂亮 - 在动画期间导致半高?

jquery - HTML:&lt;input&gt; 元素在用户输入后改变位置

html - CSS 列内容消失在页脚后面

javascript - 幻灯片更改时的 jquery 循环触发事件不在之前或之后

Javascript:如何使用单选按钮在两个 div 之间显示/隐藏?

jquery - 不倾斜导航栏下拉仅 HTML5/CSS/jQuery