目标是将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>
答案 0 :(得分:0)
您的范围是错误的。您将创建所有 .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);
});
要由您自己决定。