【问题标题】:dom wrapping a substring in textnode with a new span nodedom 用新的 span 节点在 textnode 中包装子字符串
【发布时间】:2011-05-01 17:28:52
【问题描述】:

假设,我有这一段:

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

我想用图像元素替换http://lol/atme.png。 我怎么做? 这就像删除文本,但添加一个图像元素来代替该文本。

我们将不胜感激。

【问题讨论】:

  • 不清楚为什么需要 XPath...

标签: javascript dom


【解决方案1】:

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

第二部分是在文本节点中进行替换的代码。前几天我answered a related question 有一些可重用的代码,现在我要重用它了。耶。

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">

【讨论】:

  • 这不是很长的说法:(e = document.getElementsByClassName('pln')[0]).innerHTML = e.innerHTML.replace(/[a-z]{3,}:\/\/[^\s]+/g, function(s) { return "&lt;img src=\""+s+"\"/&gt;" })(你可以在控制台中运行它,顺便说一句)
  • @Orwellophile:我想在这种情况下是这样,只要您处理的是没有嵌套元素的单个元素。
【解决方案2】:

我可能误解了你的问题。 据我了解,可以使用 div 作为占位符

//HTML
<p>
    <div id="holder"><a>link to image</a></div></p>

//js
var h = document.getElementById("holder");
if(h)h.innerHTML = "<img.....>" //the image tag

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 2020-03-16
    • 2021-12-06
    相关资源
    最近更新 更多