将<href=>链接替换为<img src=>图像

Replace <a href=> links to <img src=> images

本文关键字:img src 图像 替换 链接 href      更新时间:2023-09-26

我正在寻找一种查找/替换图像链接的方法。

例如,以下文本:

<a href="http://domain.com/arbitrary-file.jpg">Text</a>

<img src="http://domain.com/arbitrary-file.jpg" />

这是在jQuery中执行此操作的最简单方法:

$("a").each(function() {
  $(this).replaceWith("<img src='" + $(this).attr("href") + "'>")
})

图片标签没有内部文本。所以你会把<a href="http://placehold.it/255x255">Something</a>变成<img src="http://placehold.it/255x255">

编辑:如果您想添加替代文本作为内部文本,您可以执行以下操作:

$("a").each(function() {
  $(this).replaceWith("<img src='" + $(this).attr("href") + "' alt='" + $(this).text() +"'>")
})

下面是您可以运行的代码段:

$("a").each(function() {
  $(this).replaceWith("<img src='" + $(this).attr("href") + "' alt='" + $(this).text() +"'>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://placehold.it/255x230">Text</a>

var linksNodes = document.getElementsByTagName('a');
for( var i = 0; i < linksNodes.length; i++ ) {
    var a = linksNodes[i];
    if( a.href.endsWith(".jpg") || a.href.endsWith(".png") ) {
        var img = document.createElement('img');
        img.src = a.href;
        a.parentElement.replaceChild( img, a );
    }
}

endsWith在ES6中,但IE11不支持它,但是Edge支持它。您可能需要扩展String

if( !String.prototype.endsWith ) {
    String.prototype.endsWith = function(value) {
        var expectedIdx = this.length - value.length;
        return this.indexOf( value, expectedIdx  ) == expectedIdx;
    }
}
<a href="http://domain.com/arbitrary-file.jpg" class="test">Text</a>
<script type="text/javascript">
  jQuery(document).ready(function(){
var attrib = jQuery('a.test').attr('href');
jQuery('a.test').removeAttr('href');
jQuery('a.test').attr('src',attrib);
  });  

试试这个:

var links = document.getElementsByTagName('a');
var i;
var currentLink;
var newImg;
for (i=0; i<links.length; i++) {
    currentLink = links[i];
    newImg = document.createElement('img');
    newImg.src = currentLink.href;
    currentLink.parentNode.insertBefore(newImg, currentLink);
    currentLink.remove();
}

可以使用 Jquery。

斯捷帕:

  1. 首先<a>标签放入div标签中。为div标记提供唯一 id:
    <div id='divtag'><a href="http://domain.com/arbitrary-file.jpg">Text</a> </div>

  2. var value= $('#divtag a').attr('href')

  3. $('#divtag').text('<img src="+ value +">Text</img>') .

按照上述步骤根据需要完成工作。