此功能来自w3school的W3.js。
此功能应该通过在搜索框中键入来过滤项目列表。 出于某种原因,这包括搜索中的html而不是innerHTML中的文本。
E.g。搜索<td>
将返回所有行。如何仅使用元素中的文本?
"use strict";
var w3 = {};
w3.getElements = function (id) {
if (typeof id == "object") {
return [id];
} else {
return document.querySelectorAll(id);
}
};
w3.filterHTML = function(id, sel, filter) {
var a, b, c, i, ii, iii, hit;
a = w3.getElements(id);
for (i = 0; i < a.length; i++) {
b = w3.getElements(sel);
for (ii = 0; ii < b.length; ii++) {
hit = 0;
if (b[ii].innerHTML.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
hit = 1;
}
c = b[ii].getElementsByTagName("*");
for (iii = 0; iii < c.length; iii++) {
if (c[iii].innerHTML.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
hit = 1;
}
}
if (hit == 1) {
b[ii].style.display = "";
} else {
b[ii].style.display = "none";
}
}
}
};
<input oninput="w3.filterHTML('#id01', '.item', this.value)" placeholder="Search for names..">
<table id="id01" border="1">
<tr>
<th>Customer</th>
<th>City</th>
<th>Country</th>
</tr>
<tr class="item">
<td>John Doe</td>
<td>Berlin</td>
<td>Germany</td>
</tr>
<tr class="item">
<td>Berglunds snabbköp</td>
<td>Luleå</td>
<td>Sweden</td>
</tr>
<tr class="item">
<td>Centro comercial Moctezuma</td>
<td>México D.F.</td>
<td>Mexico</td>
</tr>
</table>
答案 0 :(得分:1)
innerText
代替innerHTML
是一种简单的方法。虽然这最初只在Internet Explorer中使用,但现在它已经在所有主流浏览器中,并且是HTML DOM标准的一部分。
"use strict";
var w3 = {};
w3.getElements = function (id) {
if (typeof id == "object") {
return [id];
} else {
return document.querySelectorAll(id);
}
};
w3.filterHTML = function(id, sel, filter) {
var a, b, c, i, ii, iii, hit;
a = w3.getElements(id);
for (i = 0; i < a.length; i++) {
b = w3.getElements(sel);
for (ii = 0; ii < b.length; ii++) {
hit = 0;
if (b[ii].innerText.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
hit = 1;
}
c = b[ii].getElementsByTagName("*");
for (iii = 0; iii < c.length; iii++) {
if (c[iii].innerText.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
hit = 1;
}
}
if (hit == 1) {
b[ii].style.display = "";
} else {
b[ii].style.display = "none";
}
}
}
};
<input oninput="w3.filterHTML('#id01', '.item', this.value)" placeholder="Search for names..">
<table id="id01" border="1">
<tr>
<th>Customer</th>
<th>City</th>
<th>Country</th>
</tr>
<tr class="item">
<td>John Doe</td>
<td>Berlin</td>
<td>Germany</td>
</tr>
<tr class="item">
<td>Berglunds snabbköp</td>
<td>Luleå</td>
<td>Sweden</td>
</tr>
<tr class="item">
<td>Centro comercial Moctezuma</td>
<td>México D.F.</td>
<td>Mexico</td>
</tr>
</table>