繁体   English   中英

javascript - 更改 w3 示例表过滤器以支持多个文本输入

[英]javascript - Altering w3 example table filter to support multiple text inputs

我在学习PHP,离理解javascript还很远,很远。 我需要帮助了解如何使用 javascript 过滤 HTML 表。 这是我在做什么的简要说明。

我正在将 URL 和标题列表放入数组中。

    $html_results[$html_int][0] = $link->getAttribute('href');
    $html_results[$html_int][1] = $link->nodeValue;

为了打印这些结果,我使用 function 来构建表格。

 function build_table($html_results){
    echo '<table id="urlTable">';
    echo '<tr class="header">';
    echo '<th style="width:70%;">URL</th>';
    echo '<th style="width:40%;">TITLE</th>';
    echo '</tr>';

    for($i=0;$i<count($html_results);$i++) {
      echo('<tr>');
      echo('<td>' . $html_results[$i][0] . '</td>');
      echo('<td>' . $html_results[$i][1] . '</td>');
      echo('</tr>');
    }
    "</table>";

这很好用,但现在我需要在不重新加载页面的情况下过滤这些结果。 我创建了两个文本字段,如下例所示:

input type="text" id="URLFilter" onkeyup="myFunction()" placeholder="Filter URLs.."
input type="text" id="TitleFilter" onkeyup="myFunction()" placeholder="Filter Titles.."

我尝试使用来自 w3schools 的 function:

<script>
function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("URLFilter");
  filter = input.value.toUpperCase();
  table = document.getElementById("urlTable");
  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>

这个脚本运行良好。 我可以过滤表,但它仅适用于表中的第一列和 URLFilter 输入。 我需要帮助理解的是如何将此 function 修改为:

  • 使用 URLFilter 输入过滤表中的第一列。 该脚本应显示包含 URLFilter 的行
  • 使用 TitleFilter 输入过滤表中的第二列。 该脚本应隐藏包含 TitleFilter 的行
  • 同时使用两个过滤器而不重新加载表格

我不介意是否需要调用两个单独的脚本才能使其工作。 我尝试制作两个脚本,但表格总是重置并且没有组合两个过滤器。 我还需要一种方法将过滤表中的结果存储到另一个 PHP 数组中,我想将其保存到数据库中。 长篇大论请见谅,提前致谢!

要组合过滤器,您需要在更改URLFilterTitleFilter的值时应用这两个过滤器,这样您只需要 1 个 function。 下面的代码比较两个输入值,如果其中 1 个不匹配,则隐藏该行。

function myFunction() {
  var url = document.getElementById("URLFilter").value,
      title = document.getElementById("TitleFilter").value,
      table = document.getElementById("urlTable"),
      matchURL = true,
      matchTitle = true;

  for(var i = 0; i < table.rows.length; i++) { // loop over table rows
    table.rows[i].style.display = ''; // show row

    matchURL = (url == '' || table.rows[i].cells[0].innerText.toUpperCase().indexOf(url) > -1);
    matchTitle = (title == '' || table.rows[i].cells[1].innerText.toUpperCase().indexOf(title) > -1);

    if(!matchURL || !matchTitle) {
      table.rows[i].style.display = 'none'; // hide row
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM