我正在尝试使用 JS 将特定单词动态替换为某个 HTML 元素中的链接。我想我会使用一个简单的正则表达式:
var regEx = new RegExp('\\b'+text+'\\b', 'gi');
在上下文 div 的 innerHTML
属性上应用 RegEx 替换的快速'n'nasty 方法:
context.innerHTML = context.innerHTML.replace(regEx, '<a href="#">'+text+"</a>");
问题在于它也适用于图像标题,从而破坏了页面布局。我希望它只应用于页面的文本,如果可能的话还排除诸如标题标签之类的内容,当然还有 HTML 注释等。
所以我尝试了类似的方法,但它似乎根本不起作用:
function replaceText(context, regEx, replace) {
var childNodes = context.childNodes;
for (n in childNodes) {
console.log(childNodes[n].nodeName);
if (childNodes[n] instanceof Text) {
childNodes[n].textContent = childNodes[n].textContent.replace(regEx, replace);
} else if (childNodes[n] instanceof HTMLElement) {
replaceText(childNodes[n], regEx, replace);
console.log('Entering '+childNodes[n].nodeName);
} else {
console.log('Skipping '+childNodes[n].nodeName);
}
}
}
谁能看出我做错了什么,或者想出更好的解决方案?谢谢!
更新:
下面是 context
内容的片段:
<h4>Newton's Laws of Motion</h4>
<p><span class="inline_title">Law No.1</span>: <span class="caption">An object at rest will remain at rest, and an object in motion will continue to move at constant velocity, unless a net force is applied.</span></p>
<ul>Consequences: <li>Conservation of Momentum in both elastic and inelastic collisions</li>
<li>Conservation of kinetic energy in elastic collisions but not inelastic.</li>
<li>Conservation of angular momentum.</li>
</ul>
<h5>Equations</h5>
<p class="equation">ρ = mv</p>
<p>where ρ is the momentum, and m is the mass of an object moving at constant velocity v.</p>
最佳答案
你可以使用这个:
function replaceText(context, regEx, replace)
{
var childNodes = context.childNodes;
for (var i = 0; i<childNodes.length; i++) {
var childNode = childNodes[i];
if (childNode.nodeType === 3) // 3 is for text node
childNode.nodeValue = childNode.nodeValue.replace(regEx, replace);
else if (childNode.nodeType === 1 && childNode.nodeName != "HEAD")
replaceText(childNode, regEx, replace);
}
}
replaceText(context, /cons/ig, 'GROUIK!');
想法是在“上下文”DOM 树中找到所有文本节点,这就是我使用递归函数在子节点内搜索文本节点的原因。
注意:我在函数中测试了childNode.nodeName != "HEAD"
。这只是避免特定标签的示例。在现实生活中,将 body 节点作为函数的参数更为简单。
关于javascript - 对元素中的所有文本应用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20730130/