用Javascript中的HTML文本替换textNode? [英] Replace a textNode with HTML text in Javascript?

查看:631
本文介绍了用Javascript中的HTML文本替换textNode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被引导到GitHub上的Linkify项目( https://github.com/cowboy/javascript-linkify ),用于查找和链接只是浮动在文本中的网址和域。

I was directed to the Linkify project on GitHub (https://github.com/cowboy/javascript-linkify) for finding and "linkifying" URLs and domains just floating in text.

真棒!它完全适用于文本!

It's awesome! It totally works on text!

但是,我不太确定如何使它在具有我想要Linkify的文本的textNode上工作。

However, I'm not quite sure how to make it work on a textNode which has the text I want to Linkify.

我明白textNode只有textContent,因为它是全部文本。由于这个Linkify函数将HTML作为文本返回,有没有办法获得textNode,并用Linkify输出重写它中的HTML?

I understand the textNode only has textContent since.. it's all text. Since this Linkify function returns HTML as text, is there a way to take a textNode and "rewrite" the HTML within it with the Linkify output?

我一直在玩与它在JSFiddle这里: http://jsfiddle.net/AMhRK/9/

I've been playing with it on JSFiddle here: 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);
    }
}
}


推荐答案

您需要将textNode替换为HTML元素,例如跨度,然后将链接文本设置为该元素的innerHTML。

You'll need to replace the textNode with an HTML element, like a span, and then set your linkified-text as that element's innerHTML.

var replacementNode = document.createElement('span');
replacementNode.innerHTML = linkify(n.textContent);
n.parentNode.insertBefore(replacementNode, n);
n.parentNode.removeChild(n);

这篇关于用Javascript中的HTML文本替换textNode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆