JQuery在<img>周围添加标签<a>

Sim*_*mon 5 jquery

如何使用JQuery添加带有该图像链接的标记aroud?

T.J*_*der 21

这将包含一组带有链接的图像:

$('some selector for the images').each(function() {
    $(this).wrap("<a href='" + this.src + "'/>");
});
Run Code Online (Sandbox Code Playgroud)

...使用.each(链接),.wrap(链接)和图像元素的本机DOM src(链接)属性.

编辑或Pointy指出(但没有尖锐),只需将一个函数传递给wrap:

$('some selector for the images').wrap(function() {
  return "<a href='" + this.src + "'/>";
});
Run Code Online (Sandbox Code Playgroud)

实例

  • 也可以使用`.wrap()`将函数作为参数; 可能洗了. (4认同)

DoX*_*icK 6

$('#img').each(function(){
    var $this = $(this); 
    $this.wrap('<a href="' + $this.attr('src') + '"></a>');
});
Run Code Online (Sandbox Code Playgroud)

  • 不,布鲁诺是对的.你在一个元素上调用每个元素.它应该是$('img'). (2认同)