Jquery 如何分别克隆父级的每个div

Jquery 如何分别克隆父级的每个div,jquery,Jquery,目标是将a标记克隆到我的代码段。问题是,所有克隆的元素都位于同一个div中,而不是它们各自的div中 我试图循环它们,但每个克隆人都坐在同一个div上 <div class="product_image_wrapper"> <a href="socks.html"> <img src="socks.jpg"> </a> <div class="mysnippet"> // The objective he

目标是将a标记克隆到我的代码段。问题是,所有克隆的元素都位于同一个div中,而不是它们各自的div中

我试图循环它们,但每个克隆人都坐在同一个div上

<div class="product_image_wrapper">
    <a href="socks.html">
    <img src="socks.jpg">
    </a>
    <div class="mysnippet"> // The objective here is that while we hover image above, then 'view product' will be shown. If user click, it will redirect to that a link. 
        <div class="myview">
            <a href="#">View product</a> // The a tag with socks.html should be cloned here
        </div> 
    </div>
</div>

<div class="product_image_wrapper">
    <a href="jean.html">
    <img src="jean.jpg">
    </a>
    <div class="mysnippet"> // Likewise this mysnippet should clone only the a tag that's it's under. 
        <div class="myview">
            <a href="#">View product</a> // The a tag with jean.html should be cloned here
        </div> 
    </div>
</div>

<div class="product_image_wrapper">
    <a href="socks.html">
    <img src="socks.jpg">
    </a>
    <div class="mysnippet"> 
        <div class="myview">
            <a href="#">View product</a>
            <a href="socks.html"><img src="socks.jpg"></a>
        </div> 
    </div>
</div>

<div class="product_image_wrapper">
    <a href="jean.html">
    <img src="jean.jpg">
    </a>
    <div class="mysnippet"> 
        <div class="myview">
            <a href="#">View product</a>
            <a href="jean.html"><img src="jean.jpg"></a>
        </div> 
    </div>
</div>

//这里的目标是,当我们将图像悬停在上面时,将显示“查看产品”。如果用户单击,它将重定向到该链接。
//带有socks.html的a标记应该在此处克隆
//同样,这个mysnippet应该只克隆它所在的a标签。
//带有jean.html的a标记应该在这里克隆

您的范围错误。创建所有.product\u image\u包装a的克隆,并将其放入第一个.myview中。但是我想你想把它放到你克隆的a旁边的.myview中,对吗

试试这个:

$('.product_image_wrapper a').each(function (e) { 
  // clone the element
  var clone = $(this).clone(); 
  // get the parent wrapper
  var wrapper = $(e).closest('.product_image_wrapper');
  // get myview
  var myview = wrapper.find('.myview');
  // prepend the clone
  myview.prepend(clone); 
});
我最喜欢的是直接对家长进行操作。因此,您以后不必搜索它:

// don't pick the "a" but the parent "product_image_wrapper"
$('.product_image_wrapper').each(function (e) { 
  // clone the element
  var clone = $(this).find('a').clone(); 
  // get myview
  var myview = $(e).find('.myview');
  // prepend the clone
  myview.prepend(clone); 
});

这取决于您想要哪一个。

请同时显示您的jquery代码,以便我们可以看到您是如何克隆的,我们可以帮助您。$('.product_image_wrapper a')。每个(函数(e){var clone=$(this.clone();$('.myview')。prepend(clone););