我正在开发一个函数来突出显示 div 中的 html,我之前已经检查了一些答案,但我没有找到任何解决方案。问题是,我的功能实际上不能同时使用 2 对 html 标签,例如:
有这个html代码:
<span>Les malalties vasculars cerebrals (MVC)
conegudes també com a <i>feridures o ictus</i> representen la tercera causa de
这个函数使用jquery
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.length && pat && pat.length ? this.each(function() {
innerHighlight(this, pat.toUpperCase());
}) : this;
};
jQuery.fn.removeHighlight = function() {
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};
- 列表项
如果我搜索:“Les”效果好。
如果我搜索:“feridures”也可以正常。
但如果我搜索“com a feridures”,该功能不会突出显示我的文本。
这是我完成申请所需的唯一东西。
最佳答案
问题不在于 HTML 标签,但它与两个标签无关。事实上,您的应用程序正在搜索文字文本,这意味着它找到的是“com a feridures”而不是“com a feridures”,因此没有匹配项。
您可以先使用 jQuery 从 span 中剥离 HTML,然后它会起作用。
$(".highlight").html( $(".highlight").text() );
关于javascript - 使用javascript突出显示html文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15417739/