如何在具有相同 src 的图像上自动添加 href

How to automatically add href on image with its same src?

本文关键字:图像 href 添加 src      更新时间:2023-09-26

如何自动将具有相同src和自定义title属性的href添加到图像div上的每个图像?

我需要转换自定义div上的每个图像,例如:

<div id="galery">
  <img src="images/img.jpg">
</div>

<div id="galery">
  <a href="images/img.jpg"><img src="images/img.jpg" title="a title"></a>
  <p>title</p>
</div>
您可以使用

after() 函数在图像后添加标题,并使用 wrap() 函数用超链接包围图像:

$("#galery img").each(function() {
  this.title = "a title";
  $(this).after("<p>title</p>");
  $(this).wrap('<a href="' + this.src + '"></a>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="galery">
  <img src="http://placehold.it/30x30" />
  <img src="http://placehold.it/40x40" />
  <img src="http://placehold.it/50x50" />
</div>

你可以使用这个:

var $img = jQuery("#galery img");
var $anchor = jQuery("<a title='a title'>").attr("href", $img.attr("src"));
$img.wrap($anchor).parent().after("<p>title</p>");

或者要处理多个图像,您可以使用:

jQuery("#galery img").each(function() {
    var $img = $(this);
    var $anchor = jQuery("<a title='a title'>").attr("href", $img.attr("src"));
    $img.wrap($anchor).parent().after("<p>title</p>");
});