我试图根据文本是否与从数据库接收的字符串匹配来突出显示文本。为了说明这个问题,这里有一个例子。 鉴于此文本:
<div class='text'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
这段文字:
<div id='matchingHighlight'>
Lorem ipsum <!-- Highlight this text within <div id='text'></div> !-->
</div>
如何突出显示 .text
中与 #matchingHighlight
(Lorem ipsum) 中的文本匹配的文本?
最佳答案
要“突出显示”关键字/短语,您需要将其包裹在任何内联元素周围。我建议您使用 <span>
标签。
以下逻辑将用 span
内包含的相同文本替换文本。类别为 .highlight
的标签
$(document).ready(function() {
var $text = $('.text');
var textToHighlight = $('#matchingHighlight').text().trim();
var textCurrent = $text.html().trim();
var isTextExists = textCurrent.indexOf(textToHighlight) > -1;
if(isTextExists) {
textCurrent = textCurrent.replace(textToHighlight, "<span class='highlight'>" + textToHighlight + "</span>");
$text.html(textCurrent);
}
});
然后您可以使用 css 对其进行样式设置,例如
.highlight {
background: yellow;
}
关于javascript - 根据与另一个字符串的匹配突出显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57565950/