Jip*_*ers 17 html javascript textnode
我被引导到GitHub上的Linkify项目(https://github.com/cowboy/javascript-linkify),用于查找和"链接"仅浮动在文本中的URL和域.
这很棒!它完全适用于文本!
但是,我不太确定如何使它在具有我想要Linkify的文本的textNode上工作.
我理解textNode只有textContent,因为它是所有文本.由于此Linkify函数将HTML作为文本返回,有没有办法获取textNode并使用Linkify输出"重写"其中的HTML?
我一直在JSFiddle上玩它:http://jsfiddle.net/AMhRK/9/
function repl(node) {
var nodes=node.childNodes;
for (var i=0, m=nodes.length; i<m; i++)
{
var n=nodes[i];
if (n.nodeType==n.TEXT_NODE)
{
// do some swappy text to html here?
n.textContent = linkify(n.textContent);
}
else
{
repl(n);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Wil*_*ott 17
您需要将textNode替换为HTML元素(如span),然后将链接文本设置为该元素的innerHTML.
var replacementNode = document.createElement('span');
replacementNode.innerHTML = linkify(n.textContent);
n.parentNode.insertBefore(replacementNode, n);
n.parentNode.removeChild(n);
Run Code Online (Sandbox Code Playgroud)
除了先前的答案外,我还建议了更短的方法(基于jQuery):
$(n).replaceWith('Some text with <b>html</b> support');
Run Code Online (Sandbox Code Playgroud)
其中n
-是textNode。
或本机版本
var txt = document.createElement("span");
txt.innerHTML = "Some text with <b>html</b> support";
node.replaceWith(txt);
Run Code Online (Sandbox Code Playgroud)
node
textNode 在哪里
小智 5
基于@AlexJeffcott 的答案:Perf 优化版本利用DocumentFragment,而不是乱搞<span>
、innerHTML 和 childNodes
const enhanceNodes = (textNodes) => {
textNodes.forEach((node) => {
const oldText = node.textContent;
const newText = fancyTextTranformation(oldText);
const fragment = document.createRange().createContextualFragment(newText);
node.replaceWith(fragment);
})
}
Run Code Online (Sandbox Code Playgroud)