내 응용 프로그램에 다음 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";
}
}
Protips : 들여 쓰기를 깨끗하게 유지 textContent
하고이 시나리오에서 더 잘 맞습니다.
tr[i].textContent
열 내용을 연결하므로 검색을 시도하지 마십시오 . 따라서 last_name 열에 "juan"이 있고 phone_no 열에 "0411"이 있으면 "an04"를 검색하면 양수가 반환됩니다. 이런 일이 일어나기를 원하지 않는 것 같습니다. 각 열 내용을 개별적으로 검색하는 것이 좋습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다