【问题标题】:replace image src text with img用 img 替换图像 src 文本
【发布时间】:2012-01-05 18:29:19
【问题描述】:

如果 HTML 代码是

<div class="photos">
http://myweb.com/imgs/img1.jpg
https://myweb.com/imgs/img2.gif
http://myweb.com/imgs/img3.png
https://myweb.com/imgs/img4.bmp
</div>

您如何通过 jquery 提取任何以 http:// OR https:// 开头并以 .jpg .gif .png 或 .bmp 结尾的网址并设置它们作为图像

<div class="photos">
<img src="http://myweb.com/imgs/img1.jpg"/>
<img src="https://myweb.com/imgs/img2.gif"/>
<img src="http://myweb.com/imgs/img3.png"/>
<img src="https://myweb.com/imgs/img4.bmp"/>
</div>

【问题讨论】:

  • 你有没有尝试过? .replace() 听起来很简单

标签: javascript jquery image src


【解决方案1】:

读出 div 的内容。匹配 url 并将 div 的内容替换为图片:

$(".photos").each(function() {
    var images = $(this).html(),
        imgs = images.match(/https?:[^\s]+/g),
        html = "";
    for (var i=0; i<imgs.length; i++)
    {
        html += '<img src="'+imgs[i]+'"/>'+"\n";
    }
    $(this).html(html);
});

你可以在这里测试它:http://jsfiddle.net/inti/ez6WE/

编辑:更好的解决方案是将原始内容中的 url 替换为图片:

$(".photos").each(function() {
    var images = $(this).html(),
        imgs = images.match(/https?:[^\s]+/g);
    for (var i=0; i<imgs.length; i++)
    {
        images = images.replace(imgs[i], '<img src="'+imgs[i]+'"/>');
    }
    $(this).html(images);
});

在这里试试:http://jsfiddle.net/inti/ez6WE/5/

编辑 2: 确保只匹配您想要显示的图像,必须像这样调整正则表达式:/https?:[^\s]+\.(jpg|gif|png|bmp)/g(@MrMisterMan 的好点)

【讨论】:

  • 如果其中一个网址不是图片怎么办?
  • 这是不正确的,它没有考虑文件扩展名,它会尝试为image1.foo创建一个图像
  • 更正了我在 Edit 2 中的答案。谢谢指出,你们俩:)
【解决方案2】:

这是一个您可以使用的正则表达式:

/^(https?://.+?\.(jpg|gif|png|bmp))$/gm 并替换为 &lt;img src="$1" /&gt;

这里的例子:http://regexr.com?2v9r2

在 Mozilla 开发者网络 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp 上阅读 RegExp

【讨论】:

    【解决方案3】:

    这样就可以了..

    $('.photos').html(function(index, html){
        return html.replace(/(http\S+\.(jpg|gif|png|bmp))/gim,'<img src="$1" />');
    });
    

    演示地址 http://jsfiddle.net/gaby/K2nQJ/

    【讨论】:

    • 哇,jQuery 什么时候接受回调作为 .html() 的参数?它甚至不在文档中。在 jsfiddle 中,它在 1.4 版以下不起作用,所以我认为这是里程碑,可惜我不知道这一点。谢谢! +1
    • 太棒了,我不知道 .html() 可以有参数
    • @inti,它在文档中 ..api.jquery.com/html/#html2 确实是在 1.4 时添加的
    • @Gaby 是 API 文档(我不知道)。我在这里查看此文档:docs.jquery.com/Html
    • @inti,您是否手动访问这些文档?因为从菜单他们重定向到api.jquery.com 页面..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2016-03-09
    • 2017-01-10
    • 1970-01-01
    相关资源
    最近更新 更多