【问题标题】:Replacing <img> tags with links to their content jquery用指向其内容 jquery 的链接替换 ​​<img> 标签
【发布时间】:2017-12-22 18:05:13
【问题描述】:

正如标题所说,我在使用 jquery 将图像转换为链接时遇到了一些问题。我现在的代码是:

var all_img =  $(".message .content").find("img");

$.each(all_img, function (index, value) {
    var src = value.src;
    value.replaceWith($("<a href='" + src +"'>Image  " + index+1 + "</a>"));
});

这会导致图像被[object Object] 替换。我也试过:

$.each(all_img, function (index, value) {
    var src = value.src;
    value.replaceWith("<a href='" + src +"'>Image  " + index+1 + "</a>");
});

这会导致我尝试插入的 html 以纯文本的形式进入。我是否误解了.replaceWith() 的工作原理?

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

你不能在value 上调用jQuery .replaceWith() 方法,你需要使用一个jQuery 对象,在你需要使用$(this) 的每次迭代中定位当前的img 像:

all_img.each(function (index, value) {
    var src = value.src;
    $(this).replaceWith("<a href='" + src +"'>Image  " + index+1 + "</a>");
});

【讨论】:

  • 或者你也可以$(value).replaceWith(...);
【解决方案2】:

我认为最好创建一个新元素并删除/隐藏 img:

$('.turnInAnchor').click(function(e){
  $('img').each(function(index, el) {
     $('body')
    .append("<a href='"+el.src+"' target='_blank'>Image "+index+"</a>");
    el.remove();

  })
})
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="turnInAnchor">Turn in anchor</button>
<img src="https://upload.wikimedia.org/wikipedia/it/7/75/Twin_Peaks_Episodio_Pilota_Laura_Palmer.png" />

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2013-12-07
    • 1970-01-01
    • 2021-08-01
    • 2022-12-08
    • 2018-11-25
    • 2015-10-05
    • 2019-03-22
    • 2013-05-26
    相关资源
    最近更新 更多