如何转换<a> tag has image URL in href to <img/> tag using jquery?

时间:2017-03-13 16:56:16

标签: javascript jquery html image anchor

I have HTML contain multiple <a> tag that has image URL in href attribute. I want to convert that <a> to <img> tag and href attribute convert to src and text of anchor set in alt attribute of the image as shown in the bottom.

<a href="https://i.stack.imgur.com/va6oM.jpg">jpg image</a>
<a href="https://i.stack.imgur.com/4aCuV.png">png image</a>
<a href="http://stackoverflow.com">stackoverflow</a>

Should convert to

<img src="https://i.stack.imgur.com/va6oM.jpg" alt="jpg image" />
<img src="https://i.stack.imgur.com/4aCuV.png" alt="png image" />
<a href="http://stackoverflow.com">stackoverflow</a>

How can I do this work?

3 个答案:

答案 0 :(得分:0)

你应该迭代每个标签。

$('a').each(function(i, a) {
   var src, txt;

   src = $(a).attr('src');
   txt = $(a).text(); // or .html()

   // now lets replace the <a> with <img>
   $(a).replaceWith('<img src="' + src + '" alt="' + txt + '">');
});

希望这会对你有所帮助

答案 1 :(得分:0)

使用匹配的attribute selector

  

[attr $ = value]

     

表示属性名称为attr且最后一个的元素   值的后缀为“value”。

(function() {
  var anchors = $("[href$='.jpg'], [href$='.png']"),
    i = 0,
    len = anchors.length;

  for (i, len; i < len; i++) {
    var anchor = $(anchors[i]),
      href = anchor.attr('href'),
      text = anchor.text(),
      img = $("<img/>", {
        src: href,
        alt: text
      });
    anchor.replaceWith(img);
  }

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://i.stack.imgur.com/va6oM.jpg">jpg image</a>
<a href="https://i.stack.imgur.com/4aCuV.png">png image</a>
<a href="http://stackoverflow.com">stackoverflow</a>

答案 2 :(得分:-1)

You can select anchor tag contain image URL using jQuery Attribute Ends With Selector [name$=”value”]

$("a[href$='.jpg'], a[href$='.JPEG'], a[href$='.png'], a[href$='.gif']").someFunction();

或在.filter()

中使用正则表达式
$("a").filter(function(){
  return this.href.match(/.(jpg|JPEG|png|gif)$/);
}).someFunction();

然后,您需要使用.replaceWith()

将所选标记转换为新标记
selectedAnchor.replaceWith(function(){
  return '<img src="'+ this.href +'" alt="'+ this.textContent +'" />';
});

&#13;
&#13;
$("a").filter(function(){
  return this.href.match(/.(jpg|JPEG|png|gif)$/);
}).replaceWith(function(){
  return '<img src="'+ this.href +'" alt="'+ this.textContent +'" />';
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://i.stack.imgur.com/EKb5k.png">png image</a>
<a href="http://stackoverflow.com">stackoverflow</a>
&#13;
&#13;
&#13;