Andreas Josas 给出的答案相当不错。然而,当搜索词在同一个文本节点中出现多次时,代码有几个错误。这是修复了这些错误的解决方案,此外,插入被分解为 matchText 以便于使用和理解。现在只在回调中构造了新标签,并通过 return 传回 matchText。
更新了 matchText 函数并修复了错误:
var matchText = function(node, regex, callback, excludeElements) {
excludeElements || (excludeElements = ['script', 'style', 'iframe', 'canvas']);
var child = node.firstChild;
while (child) {
switch (child.nodeType) {
case 1:
if (excludeElements.indexOf(child.tagName.toLowerCase()) > -1)
break;
matchText(child, regex, callback, excludeElements);
break;
case 3:
var bk = 0;
child.data.replace(regex, function(all) {
var args = [].slice.call(arguments),
offset = args[args.length - 2],
newTextNode = child.splitText(offset+bk), tag;
bk -= child.data.length + all.length;
newTextNode.data = newTextNode.data.substr(all.length);
tag = callback.apply(window, [child].concat(args));
child.parentNode.insertBefore(tag, newTextNode);
child = newTextNode;
});
regex.lastIndex = 0;
break;
}
child = child.nextSibling;
}
return node;
};
用法:
matchText(document.getElementsByTagName("article")[0], new RegExp("\\b" + searchTerm + "\\b", "g"), function(node, match, offset) {
var span = document.createElement("span");
span.className = "search-term";
span.textContent = match;
return span;
});
如果您希望插入锚(链接)标签而不是跨度标签,请将 create 元素更改为“a”而不是“span”,添加一行以将 href 属性添加到标签,并添加 'a'到 excludeElements 列表,这样就不会在链接中创建链接。