使用jQuery将图片链接替换为img元素

3
使用jQuery,我试图替换某个div中所有链接到图片(.jpg,.png,.tiff,.gif)的元素,用img元素来显示图片而不是链接它。
例如,它会改变以下内容:
<a href="http://domain.com/image.jpg">Any Text Here</a>

为了

<img src="http://domain.com/image.jpg"/>

非常感谢您的提前帮助 :)
2个回答

2
$('a.img').each(function(){
    //assuming they have the image class
    var img = $('<img>',{src: this.href});
    $(this).replaceWith(img);
});

请尝试一下 ^_^

更新

如果所有图片没有相同的类:

$('a').each(function(){
    var ext = getfileextension(this.href);
    switch(ext){
        case '.gif':
        case '.png':
        case '.jpg':
            var img = $('<img>',{src: this.href});
            $(this).replaceWith(img);
            break;
    }

});
function getfileextension(filename) 
{ 
    var dot = filename.lastIndexOf("."); 
    if( dot == -1 ) return ""; 
    var extension = filename.substr(dot,filename.length); 
    return extension; 
} 

看看这个示例: http://jsfiddle.net/maniator/3pXEm/

他们没有任何类。代码只需要选择以.png、.jpg、.tiff或.gif结尾的链接。 - jetlej
我必须让它变得困难 :) - jetlej
没问题,你可以按需扩展那个switch case ^_^ - Naftali
@Jordan @Neal,看看下面我的回答:你可以利用一些以“Ends-With”为选择器来大大简化此操作。 - David Fullerton

2
一个更简单的 Neal 的回答 版本,使用 属性结尾选择器
$("a[href$='.png'], a[href$='.jpg'], a[href$='.tiff'], a[href$='.gif']").each(function() {
    var img = $('<img>',{src: this.href});
    $(this).replaceWith(img);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接