javascript - javascript - 更改 w3 示例表过滤器以支持多个文本输入
问题描述
我正在学习 PHP,离理解 javascript 还很远很远。我需要帮助了解如何使用 javascript 过滤 HTML 表格。这是我在做什么的简要说明。
我正在将 URL 和标题列表放入数组中。
$html_results[$html_int][0] = $link->getAttribute('href');
$html_results[$html_int][1] = $link->nodeValue;
为了打印这些结果,我使用了一个函数来构建表格。
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 的这个功能:
<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 输入。我需要帮助理解的是如何将此功能修改为:
- 使用 URLFilter 输入过滤表中的第一列。该脚本应显示包含 URLFilter 的行
- 使用 TitleFilter 输入过滤表中的第二列。该脚本应隐藏包含 TitleFilter 的行
- 同时使用两个过滤器而不重新加载表格
我不介意是否需要调用两个单独的脚本才能使其工作。我尝试制作两个脚本,但表格总是重置并且没有组合两个过滤器。我还需要一种将过滤表中的结果存储到另一个 PHP 数组中的方法,我想将其保存到数据库中。长篇大论请见谅,提前致谢!
解决方案
URLFilter
要组合过滤器,如果您更改or的值,您需要同时应用两个过滤器,TitleFilter
因此您只需要 1 个函数。下面的代码比较两个输入值,如果其中 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
}
}
}
推荐阅读
- reactjs - 在 create-react-app 之后 React npm start 不起作用
- python - 如何在不使用 Google API 的情况下制作 Google Classroom 机器人?
- javascript - 为什么我的函数返回 Promise {
} - asciidoc - AsciiDocs docdir 返回错误的路径
- javascript - 如何从基于带有firestore的字段的集合中获取文档?
- android-studio - 如何将对象调用到 if 语句
- django - Django - 临时midi文件music21
- flutter - Flutter中方法提取、Widget提取的使用
- javascript - 在 Angular 10 中的 ngIf 条件下显示 ChartJS
- python - Pandas DataFrame 中的元素类型与过滤器不一致