简体   繁体   English

将多个图像包装在一个 <div> 在jQuery中

[英]Wrapping multiple images inside a <div> in jQuery

I need to find all the images inside a div , and wrap a div around them. 我需要在div找到所有图像,并将div包裹在它们周围。 Here's the code I come up with, but that's not working! 这是我想出的代码,但是没有用! Why? 为什么?

 jQuery(function() { my_selection = []; $('.post').each(function(i) { if ($(this).find('img').length > 1) { my_selection.push(['.post:eq(' + i + ')']); } }); $(my_selection.join(',')).wrapAll('<div class="wrapper"></div>'); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

How about something like: 怎么样:

$('.post img').wrapAll('<div class="wrapper" />');

.post img will get a collection of IMG tags within your .post container, and wrapAll applies the DIV around each of them. .post img将在您的.post容器中获取IMG标签的集合,然后wrapAllDIV应用于每个标签。

The manual page for the wrapAll function actually has quite a close example to what you want. wrapAll函数手册页实际上有一个非常接近您想要的示例。

很难说,因为我看不到您的标记,但类似:

$('.post img').wrapAll('<div class="wrapper" />');

this works! 这可行!

$('.post').each(function(){
    var container = $(this);
    $('img', container).wrapAll('<div class="slideshow" />');
});

Try this 尝试这个

 $('.post img').each(function() {
      $(this).wrap($('<div/>', { 'class': 'wrapper'}));
    });

Here is a link to the similar question I asked : 这是我问过的类似问题的链接:

Create new div arround anchor link when clicked 单击时创建新的div arround锚链接

$('img').each(function (){
   $(this).wrap('<div class="new" />');
});

Wrap a div around each img inside a .post: 在.post内的每个img周围环绕一个div:

$('.post img').wrap('<div class="wrapper" />');

Wrap a div around each post that has a img: 将每个具有img的帖子环绕div:

$('.post:has(img)').wrap('<div class="wrapper" />');

Move all divs that have an img inside a wrapper div: 将所有具有img的div移动到包装div中:

$('<div class="wrapper" />').append($('.post:has(img)'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM