想,我有这样的一段话:DOM包裹在textnode一个子一个新跨越节点
<p>this is a paragraph containing link to an image at http://lol/atme.png :)</p>
我想和图像元素来取代http://lol/atme.png
。 我该怎么做? 它像删除文本,但添加一个图像元素,而不是该文本。
帮助将不胜感激。
想,我有这样的一段话:DOM包裹在textnode一个子一个新跨越节点
<p>this is a paragraph containing link to an image at http://lol/atme.png :)</p>
我想和图像元素来取代http://lol/atme.png
。 我该怎么做? 它像删除文本,但添加一个图像元素,而不是该文本。
帮助将不胜感激。
有两个环节进行。首先是从文本中提取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(/ [az] {3,}:\/\/[^ \ s] +/g,function(s){return }}(你可以在控制台中运行它,btw) – Orwellophile 2015-04-25 21:47:52
@ Orwellophile:我想在这种情况下,只要你处理的是没有嵌套元素的单个元素。 – 2015-04-26 15:56:33
我可能会误解你的问题。 从我个人理解,可以使用一个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
目前尚不清楚为什么你需要的XPath ... – 2010-10-28 16:42:58