gpt4 book ai didi

javascript - 使用java脚本在html表中的多个索引上搜索字段

转载 作者:行者123 更新时间:2023-12-03 04:48:28 25 4
gpt4 key购买 nike

我的应用程序中有以下 Html 表

  <table class="table table-striped table-hover table-bordered" id="sample_editable_1">
<thead>
<tr>
<th>Id</th>
<th>User Name</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
<th>Gender</th>

</tr>
</thead>
<tbody>
@foreach($user as $users)
<tr>
<td>{{$users['id']}}</td>
<td>{{$users['user_name']}}</td>
<td>{{$users['first_name']}}</td>
<td>{{$users['last_name']}}</td>
<td>{{$users['phone_no']}}</td>
<td>{{$users['gender']}}</td>
@endforeach
</tbody>
</table>

我编写了以下 JavaScript 用于在此表中进行搜索

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

此特定代码适用于单个索引,例如 td = tr[i].getElementsByTagName("td")[0][1] 我怎样才能使它适用于这样一个场景:无论用户搜索表,都应该显示与输入匹配的所有内容?

最佳答案

与循环 trs 的方式相同,您应该循环 tds:

function myFunction() {
var input, filter, table, tr, td, i, ii;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("sample_editable_1");
tr = table.querySelectorAll("tbody tr");
for (i = 0; i < tr.length; i++) {
var tds = tr[i].getElementsByTagName("td");
var found = false;
for (ii = 0; ii < tds.length && !found; ii++) {
if (tds[ii].textContent.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
tr[i].style.display = found?"":"none";
}
}

专业提示:保持缩进干净,textContent 更适合这种情况。

不要尝试搜索 tr[i].textContent,因为这会连接列内容,因此,如果 last_name 列包含“juan”,phone_no 列包含“0411”,则搜索“an04” ” 将返回正值。我猜你不希望这种事发生。最好单独搜索每一列内容。

关于javascript - 使用java脚本在html表中的多个索引上搜索字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com