html - 如何过滤内容在 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 标记中的表。
解决方案
我花了很长时间才弄清楚这一点。
首先,你的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>
推荐阅读
- sql - SQL Server:选择多次使用
- python-3.x - Python中具有多线程和进程的复杂程序中的内存错误调试
- c# - 如何使用 CEF 上传文件?
- swift - 如何从具有多个部分的 NSCollectionView 添加/删除项目
- android - 如何使用 Koin 管理用户范围?
- javascript - material-ui-pickers 示例:TypeError: Object(...) is not a function
- python - 在 VisPy 中使用 on_timer 更新 SceneCanvas
- php - 这段代码Authy PHP有什么问题?
- java - javax.mail.Message getSentDate 返回 null
- excel - 从excel范围内获取最接近单元格值的值