dom在文本节点中包含一个新的跨度节点的子字符串 [英] dom wrapping a substring in textnode with a new span node

查看:111
本文介绍了dom在文本节点中包含一个新的跨度节点的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个段落:

<p>this is a paragraph containing link to an image at http://lol/atme.png :)</p>

我要替换 http://lol/atme.png 与图像元素。
我该如何做?
它像删除文本,但添加一个图像元素代替该文本。

I want to replace http://lol/atme.png with an image element. How do I do that? Its like removing the text, but adding a image element in place of that text.

帮助将不胜感激。

推荐答案

这有两个部分。第一个是从文本中提取URL,这是一个棘手的问题,我不感兴趣,我会在生产中使用这个之前做一些研究。现在,我将使用一个非常简单的说明性正则表达式。

There are two parts to this. The first is the extraction of the URLs from the text, which is a tricky issue I'm not that interested in. I would do some research before using this in production. For now, I'll use an extremely simple illustrative regex.

第二部分是在文本节点内进行替换的代码。我回答了一个相关问题另一天有一些可重用的代码,现在我正在重新使用它。 yay。

The second part is the code for doing the replacement within text nodes. I answered a related question the other day with some reusable code and now I'm getting to reuse it. Yay.

function createImage(matchedTextNode) {
    var el = document.createElement("img");
    el.src = matchedTextNode.data;
    el.width = 30;
    el.height = 20;
    return el;
}

function surroundInElement(el, regex, surrounderCreateFunc) {
    var child = el.lastChild;
    while (child) {
        if (child.nodeType == 1) {
            surroundInElement(child, regex, createImage);
        } else if (child.nodeType == 3) {
            surroundMatchingText(child, regex, surrounderCreateFunc);
        }
        child = child.previousSibling;
    }
}

function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
    var parent = textNode.parentNode;
    var result, surroundingNode, matchedTextNode, matchLength, matchedText;
    while ( textNode && (result = regex.exec(textNode.data)) ) {
        matchedTextNode = textNode.splitText(result.index);
        matchedText = result[0];
        matchLength = matchedText.length;
        textNode = (matchedTextNode.length > matchLength) ?
            matchedTextNode.splitText(matchLength) : null;
        surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
        parent.insertBefore(surroundingNode, matchedTextNode);
        parent.removeChild(matchedTextNode);
    }
}

var urlRegex = /http(s?):\/\/($|[^\s]+)/;

function replaceImageUrls(el) {
    surroundInElement(el, urlRegex, createImage);
}

<div id="s">One
    http://www.google.co.uk/images/logos/ps_logo2.png
    two
    http://www.google.co.uk/images/logos/ps_logo2.png three</div>

<input type="button" onclick="replaceImageUrls(document.getElementById('s'))" value="replace">

这篇关于dom在文本节点中包含一个新的跨度节点的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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