首页 > 解决方案 > 如何过滤内容在 div 或 span 中的 HTML 表格?

问题描述

我正在使用外部 wordpress 插件打印出地点列表(即沙龙),我想通过搜索文本字段过滤它们。该插件输出如下代码所示的表格。

我尝试了使用 tr 和 td 过滤但没有一个有效的示例,我查看了https://www.w3schools.com/howto/howto_js_filter_lists.asp并尝试编辑代码以使用 SPAN 标签,但也搜索了 stackoverflow很多。

搜索字段:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search here">

脚本:

<script>
    // taken straight from w3schools
    function myFunction() {
    // Declare variables
        var input, filter, table, tr, td, i, txtValue;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");

        // Loop through all table rows, and hide those who don't match the search query
        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>

桌子:

<table id="exampletable" class="table1">
    <tbody>
        <tr>
            <td class="placeicon">
                <img src="icon.png">
            </td>
            <td class="placetext">
                <div class="placecontrols">
                    <a href="examplemap.html"><img src="icon2.png"></a>
                </div>
                <span class="text">
                    <strong>Example Place</strong>
                    <br>Address 123
                    <br>Phone: 123456789
                </span>
            </td>
        </tr>
        <tr>...</tr>
        <tr>...</tr>

我希望搜索字段过滤名称在 SPAN 标记中的表。

标签: htmlfilterhtml-table

解决方案


我花了很长时间才弄清楚这一点。

首先,你的table和js的id不一样,请改成exampletable.

其次是代码。而不是td = tr[i].getElementsByTagName("td")[0]; 尝试td = tr[i].getElementsByTagName("strong")[0];

或者使用这个

 <script>
    // taken straight from w3schools
    function myFunction() {
    // Declare variables
        var input, filter, table, tr, td, i, txtValue;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("exampletable");
        tr = table.getElementsByTagName("tr");

        // Loop through all table rows, and hide those who don't match the search query
        for (i = 0; i < tr.length; i++) {
            td= tr[i].getElementsByTagName("strong")[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>

推荐阅读