【发布时间】:2020-03-29 09:34:48
【问题描述】:
可能已经提出过类似的问题,但请仔细阅读详细信息。
我正在使用一种自制的自动完成功能,现在我想突出显示结果集中的搜索词。 到目前为止,这有效,但仅适用于纯文本。问题是:如果结果 div 中有一个,我需要保留 html 结构。请查看我的示例:目前我正在失去包含的跨度与类粗体。我怎样才能保留它们?
感谢您的建议!
$('#box').keyup(function () {
const valThis = this.value;
const length = this.value.length;
$('.objType').each(function () {
const text = $(this).text();
const textL = text.toLowerCase();
const position = textL.indexOf(valThis.toLowerCase());
if (position !== -1) {
const matches = text.substring(position, (valThis.length + position));
const regex = new RegExp(matches, 'ig');
const highlighted = text.replace(regex, `<mark>${matches}</mark>`);
$(this).html(highlighted).show();
} else {
$(this).text(text);
$(this).hide();
}
});
});
input[type="text"] {
width: 50%;
margin:10px;
padding: 5px;
float:left;
clear:left;
}
div{
float:left;
clear:left;
margin:10px 10px;
}
.bold {
font-weight: 700;
}
table td {
border: solid 1px #ccc;
padding: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input placeholder="Filter results" id="box" type="text" />
<div class="objType" id="item1">
<span class="bold">Accepted</span> Event Relation
<table>
<tr>
<td>Lorem</td>
<td>ipsum</td>
</tr>
</table>
</div>
<div class="objType" id="item2">
Case <span class="bold">Status</span> Value
<table>
<tr>
<td>Lorem</td>
<td>ipsum</td>
</tr>
</table>
</div>
<div class="objType" id="item3">
External <span class="bold">Data Source</span>
<table>
<tr>
<td>Lorem</td>
<td>ipsum</td>
</tr>
</table>
</div>
<div class="objType" id="item4">
Navigation <span class="bold">Link</span> Set
<table>
<tr>
<td>Lorem</td>
<td>ipsum</td>
</tr>
</table>
</div>
PS:另外一个 JSFiddle 可能会有所帮助 => https://jsfiddle.net/SchweizerSchoggi/6x3ak5d0/7/
【问题讨论】:
-
一种方法是使用 Range 对象的 getClientRects 方法。见stackoverflow.com/questions/58553501/…
标签: jquery html autocomplete highlight