我尝试将代码片段集成到数据表页面中,并取得了一些成功。只有 CSS/JavaScript 表行/数据显示和隐藏不适用于我的数据表。失去了想法,但想保留马克.js在混合中突出显示效果很好。
var input, table, rows, markInstance;
window.onload = function init() {
input = document.getElementById("myInput");
table = document.getElementById('myTable');
rows = table.querySelectorAll('tr');
markInstance = new Mark(table);
clear();
}
function ContactsearchFX() {
clear();
if (input.value.length == 0) return;
filterRows(input.value);
highlightMatches(input.value);
}
function clear() {
markInstance.unmark();
for (var i = 0; i < rows.length; i++) {
rows[i].style.display = 'none';
}
}
function filterRows(text) {
var part = text.toUpperCase();
for (i = 0; i < rows.length; i++) {
var row = rows[i];
var td = row.getElementsByTagName("td")[0];
if (td) {
// part = GI
// innerHtml = <MARK DATA-MARKJS="TRUE">G</MARK>ITHUB (wont match)
// innerText = GITHUB (will match)
var content = td.innerText.toUpperCase();
if (content.includes(part)) {
row.style.display = "";
}
}
}
}
function highlightMatches(text) {
markInstance.mark(text);
}
.input-wrap {
margin-bottom: 12px;
}
.hints {
display: none;
margin-top: 12px;
}
#myInput:invalid~.hints {
display: block;
}
mark {
background: orange;
font-weight: bold;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.js"></script>
<div class="input-wrap">
<label>
Search Titles:
<input id="myInput" type="text" required
onkeyup="ContactsearchFX()"
placeholder="Search Titles" />
<span class="hints">
Hints: type "title", "details"...
</span>
</label>
</div>
<table id="myTable" style="width: 100%" class="style1">
<tr> -+- THIS IS WHERE I INSERT MY DATA TABLE -+-
<th>Title</th>
<th>Details</th>
</tr>
<tr>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td>*</td>
<td>*</td>
</tr>
</table>
如果我很了解你,你可以用简单的CSS类来隐藏它,如下所示:
.HTML
<input placeholder="Type title">
<table>
<tr class="hide">
<th>Title</th>
<th>Details</th>
</tr>
<tr class="hide">
<td>Aladdin</td>
<td>Nice</td>
</tr>
<tr class="hide">
<td>Inception</td>
<td>Cool</td>
</tr>
<tr class="hide">
<td>Fight Club</td>
<td>Great</td>
</tr>
</table>
.CSS
.hide {
display: none;
}
.JS
// Selectors
const $input = document.querySelector('input')
const $heads = document.querySelector('tr:first-of-type')
const $titles = document.querySelectorAll('td:first-of-type')
$input.oninput = () => {
// Num titles shown
let num = 0
// Find titles and show rows
$titles.forEach($t => {
const found = $input.value &&
$t.textContent.toUpperCase().includes($input.value.toUpperCase())
$t.parentElement.className = found ? '' : 'hide'
if (found) num++
})
// Show header
$heads.className = num ? '': 'hide'
}
在这里你可以检查一个工作示例:https://jsfiddle.net/0antxeum/
希望这有所帮助,或者至少为您指明正确的方向:(