开发者

Wrap <a> tags around <img /> with href = img src?

开发者 https://www.devze.com 2023-01-23 09:48 出处:网络
Trying to wrap antag around an image, addClass and input src of img as href oftag: $(document).ready(function() {

Trying to wrap an tag around an image, addClass and input src of img as href of tag:

 $(document).ready(function() {
$(".new img").each(function() {
    var src = $(this).attr('src').addClass('image');
    var a = $('<a/>').attr('href', src);
    $(this).wrap(a);
});
});

My HTML:

<img cl开发者_StackOverflowass="new" src="pic0.png" title="Image_Title"/>

Can't seem to get this to work. Any suggestions would be helpful!


Two things. Firstly, you have your selector backwards -- it should be img.new. Secondly, attr returns a string, not jQuery, so you can't chain it. Do the following and it should work:

$(document).ready(function() {
    $("img.new").each(function() {
        var $this = $(this);
        var src = $this.attr('src');
        $this.addClass('image');
        var a = $('<a/>').attr('href', src);
        $this.wrap(a);
    });
});


Your selector just needs an adjustment, this:

$(".new img")

Should be:

$("img.new")

The new class is on the <img> itself, the <img> isn't a descendant of a class="new" element, which is what your current selector is looking for. Also .attr('src') gets a string, so you need to add the class before calling it, overall like this:

$(function() {
  $("img.new").each(function() {
    var src = $(this).addClass('image').attr('src');
    var a = $('<a/>').attr('href', src);
    $(this).wrap(a);
  });
});

You can test it here, or a bit simpler/faster version here:

$(function() {
  $("img.new").each(function() {
    var a = $('<a/>').attr('href', this.src);
    $(this).addClass('image').wrap(a);
  });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消