3 回答
TA贡献1900条经验 获得超5个赞
这里有两个问题。一种是嵌套内容问题,即跨越元素边界的搜索匹配。另一个是HTML转义字符。
处理HTML转义字符的一种方法是,例如,如果您使用的是jQuery,则使用该.text()
方法,然后在该方法上运行搜索。从中返回的文本已经将转义字符“翻译”为它们的真实字符。
处理这些特殊字符的另一种方法是用转义版本替换实际字符(在搜索字符串中)。但是,由于那里存在各种各样的可能性,因此取决于实现方式,这可能是一个冗长的搜索。
可以使用相同类型的“文本”方法来查找跨越实体边界的内容匹配项。之所以变得棘手,是因为“文本”没有任何内容内容的实际部分来自何处的概念,但是如果您深入钻取,它会为您提供一个较小的域来进行搜索。一旦接近,您就可以切换到更多的“字符系列”搜索,而不是基于单词的搜索。
我不知道任何执行此操作的库。
TA贡献1805条经验 获得超9个赞
突出显示搜索关键字并使用javascript从网页中删除突出显示
<script>
function highlightAll(keyWords) {
document.getElementById('hid_search_text').value = keyWords;
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(keyWords)) {
document.execCommand("HiliteColor", false, "yellow");
sel.collapseToEnd();
}
document.designMode = "off";
goTop(keyWords,1);
}
function removeHighLight() {
var keyWords = document.getElementById('hid_search_text').value;
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(keyWords)) {
document.execCommand("HiliteColor", false, "transparent");
sel.collapseToEnd();
}
document.designMode = "off";
goTop(keyWords,0);
}
function goTop(keyWords,findFirst) {
if(window.document.location.href = '#') {
if(findFirst) {
window.find(keyWords, 0, 0, 1);
}
}
}
</script>
<style>
#search_para {
color:grey;
}
.highlight {
background-color: #FF6;
}
</style>
<div id="wrapper">
<input type="text" id="search_text" name="search_text">
<input type="hidden" id="hid_search_text" name="hid_search_text">
<input type="button" value="search" id="search" onclick="highlightAll(document.getElementById('search_text').value)" >
<input type="button" value="remove" id="remove" onclick="removeHighLight()" >
<div>
<p id="search_para">The European languages are members of the same family. Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words. Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators. To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words. If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages. The new common language will be more simple and regular than the existing European languages.</p>
</div>
</div>
添加回答
举报