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
3 Answers
Reset to default 10Because 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
版权声明:本文标题:javascript - How to wrap a link to all images inside a div? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741652242a2390547.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论