开发者

Replace links to images with img elements w/ jQuery

开发者 https://www.devze.com 2023-02-22 15:43 出处:网络
Using jQuery, I\'m trying to replace all links to images (.jpg, .png, .tiff, .gif) within a certain div with img elements to show the image instead of linking to it.

Using jQuery, I'm trying to replace all links to images (.jpg, .png, .tiff, .gif) within a certain div with img elements to show the image instead of linking to it.

Eg. it would change

<a href="http://domain.com/image.jpg">Any Text Here</a>

to

<img src="http://domain.com/image.jpg"/>开发者_如何学JAVA

Thank you so much in advance :)


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

try that ^_^

UPDATE

if all images dont have the same class:

$('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; 
} 

see this fiddle: http://jsfiddle.net/maniator/3pXEm/


A simpler version of Neal's answer, using Attribute Ends With selectors:

$("a[href$='.png'], a[href$='.jpg'], a[href$='.tiff'], a[href$='.gif']").each(function() {
    var img = $('<img>',{src: this.href});
    $(this).replaceWith(img);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消