admin管理员组

文章数量:1300005

I have something like this:

<img class="photo" src="www.example" />
<img class="photo" src="www.example2" />
<img class="photo" src="www.example3" />

And I need to get this:

<a href="www.example" class="link">
    <img class="photo" src="www.example" />
</a>
<a href="www.example2" class="link">
    <img class="photo" src="www.example2" />
</a>
<a href="www.example3" class="link">
    <img class="photo" src="www.example3" />
</a>

I need to add the link, the href with the same code as the SRC of each image, and a class.

I was trying to do it like this:

$('.photo').wrapAll('<a>');

But it doesn't even work. What am I doing wrong?

I have something like this:

<img class="photo" src="www.example." />
<img class="photo" src="www.example2." />
<img class="photo" src="www.example3." />

And I need to get this:

<a href="www.example." class="link">
    <img class="photo" src="www.example." />
</a>
<a href="www.example2." class="link">
    <img class="photo" src="www.example.2" />
</a>
<a href="www.example3." class="link">
    <img class="photo" src="www.example.3" />
</a>

I need to add the link, the href with the same code as the SRC of each image, and a class.

I was trying to do it like this:

$('.photo').wrapAll('<a>');

But it doesn't even work. What am I doing wrong?

Share Improve this question edited Apr 20, 2019 at 18:43 double-beep 5,51919 gold badges40 silver badges49 bronze badges asked Mar 28, 2012 at 15:41 AlvaroAlvaro 41.6k31 gold badges172 silver badges347 bronze badges 2
  • $('.photo').wrapAll('<a />'); ? Or $('.photo').wrapAll('<a></a>');? api.jquery./wrapAll – PeeHaa Commented Mar 28, 2012 at 15:43
  • It doesn't work. The images are loaded with jquery with: d_row.append(img); – Alvaro Commented Mar 28, 2012 at 16:53
Add a ment  | 

3 Answers 3

Reset to default 10

Because the hrefs will all be different, you'll need to use each.

$('img.photo').each( function() {
    var $img = $(this),
        href = $img.attr('src');
    $img.wrap('<a href="' + href + '" class="link"></a>');
});

Note that wrapAll isn't what you want anyway as it will take all the elements and wrap them with a single anchor tag. If you weren't using an anchor that needs a different href for each element, wrap would work by itself and wrap each one individually.

$('img').wrap("<a href='foo'>") will work just fine.

Try this:

$('.photo').before('<a href="www.example3." class="link">');
$('.photo').after('</a>');

And if you want

$( '.photo' ).each( function() {
    var mySrc = $( this ).attr( "src" );
    $( this ).before( '<a href="' + mySrc + '" class="link">' ) );
    $( this ).after( '</a>' ) );
});

I hope this works for you...

本文标签: javascriptHow to wrap a link to all images inside a divStack Overflow