[英]Javascript replace image text links with images but ignore existing IMG tags
我想用真实图像替换页面上的代码而不是图像链接。 我已经可以基于另一个stackoverflow答案做到这一点。
但我想知道是否有办法忽略IMG标签中包含的任何内容。 谢谢!
$("#photos li").each(function() {
$(this).html($(this).html().replace(/(http:\/\/\S+(\.png|\.jpg|\.gif))/g, '<a href="$1" class="fancybox" rel="gallery1"><img src="$1" /></a>'));
});
看起来列表包含一组URL,而不是链接。
$("#photos li").each(function() {
if(!$(this).find('img').length){
$(this).html($(this).html().replace(/(http:\/\/\S+(\.png|\.jpg|\.gif))/g, '<a href="$1" class="fancybox" rel="gallery1"><img src="$1" /></a>'));
}
});
这当然取决于HTML的结构。
JSFiddle 。
你不应该只是将正则表达式应用于html。 很难理解并且很难预测它有哪些副作用。 相反,您应该使用具有完全解析的DOM树的优势,并且只是传递您关心的那些元素:文本节点!
另外我建议你不要写"<img src="$1" />"
。 如果$ 1包含奇怪的东西,那么奇怪的事情就会发生。 没有必要考虑这可能导致的所有事情,因为一个非常简单的解决方法是: jQuery('<img />').attr('src', someTextWithNotTooWellCheckedContent)
。
这是一个如何工作的例子:
jQuery('#photos li').find('*').contents().filter(function() {
return this.nodeType == 3;
}).each(function(i, elem)
{
var matches = /(.*)(http:\/\/\S+(?:\.png|\.jpg|\.gif))(.*)/g.exec(elem.wholeText);
if (matches)
{
var parent = elem.parentNode;
var before = matches[1];
var replace = jQuery('<a />').attr('href', matches[2]).append(jQuery('<img />').attr('href', matches[2]))[0];
var after = matches[3];
parent.insertBefore(document.createTextNode(before), elem);
parent.insertBefore(replace, elem);
parent.insertBefore(document.createTextNode(after), elem);
parent.removeChild(elem);
}
});
在行动: http : //jsfiddle.net/B4GPt/
PS:根据你的html结构和意图,你可能需要或不需要将find('*')
替换为find('*').andSelf()
从而扩展上面的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.