【问题标题】:Replace links to images with img elements w/ jQuery使用带有 jQ​​uery 的 img 元素替换指向图像的链接
【发布时间】:2011-04-05 11:49:55
【问题描述】:

使用 jQuery,我试图用 img 元素替换某个 div 中的所有图像链接(.jpg、.png、.tiff、.gif),以显示图像而不是链接给它。

例如。它会改变

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

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

提前非常感谢你:)

【问题讨论】:

    标签: jquery


    【解决方案1】:
    $('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 结尾的 href 链接
    • 我不得不让它变得困难:)
    • noo 问题,您可以根据需要扩展该开关盒 ^_^
    • @Jordan @Neal 请参阅下面的答案:您可以使用一些 Ends-With 选择器大大简化此操作
    【解决方案2】:

    Neal's answer 的更简单版本,使用 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);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多