更新时间:2023-11-28 18:47:10
我建议你使用未充分利用的 TreeWalker DOM API,如下:
I suggest you use the under-utilized TreeWalker DOM API, as follows:
var walk = document.createTreeWalker(document, NodeFilter.SHOW_TEXT, null, false),
n;
while(n = walk.nextNode()) {
n.nodeValue = n.nodeValue.replace(/foo/g, 'bar');
}
NodeFilter.SHOW_TEXT
告诉 TreeWalker 您只对文本节点感兴趣.请参阅 https://developer.mozilla.org/en/docs/Web/API/树行者了解更多信息.
The NodeFilter.SHOW_TEXT
tells TreeWalker you only are interested in text nodes. See https://developer.mozilla.org/en/docs/Web/API/TreeWalker for more information.
但是你想用更复杂的 DOM 结构替换文本,涉及到 em
元素,所以我们需要做更多的工作:
But you want to replace the text with a more complex DOM structure, involving the em
element, so we have to do a bit more work:
function emphasize(regexp) {
var walk = document.createTreeWalker(document, NodeFilter.SHOW_TEXT, null, false),
n, span;
while (n = walk.nextNode()) {
newVal = n.nodeValue.replace(regexp, function(match) {
return "<em>" + match + "</em>";
});
if (newVal !== n.nodeValue) {
span = document.createElement('span');
span.innerHTML = newVal;
n.parentNode.replaceChild(span, n);
}
}
}
Nodewalker 可能不会很高兴将其当前节点从其下方替换掉.这需要进行一些测试和可能的调整.
It could be Nodewalker will not be too happy about having its current node being replaced out from under it. That would require a bit of testing and possible tweaking.