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

标签 jquery

目标是将 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/

相关文章:

javascript - 返回溢出内容中的子页面 anchor

jQuery 代码在 Chrome 和 IE 中无法正常工作

javascript - 如何为div添加不透明度?

jquery - 使用 jQuery 查找点击时最接近的元素

javascript - jQuery find ('#selector' ).length 导致 Chrome 控制台出错

jquery - 如何将 JQuery Datepicker 与 Django 模板语言结合使用

javascript - ASP.NET WebForms 路由 Javascript 错误

javascript - 如何在通过 AJAX 检索数据后循环每个 JSON 值

JQuery 不在 $(document).change() 上执行

javascript - 如何阻止 Javascript 级联点击事件或如何正确分配给不同的 div。