目标是将 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>
最佳答案
你的范围是错误的。您创建所有 .product_image_wrapper 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 - 如何分别克隆父级的每个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57847893/