在迭代期间复制每个容器中的图像

时间:2015-08-17 22:45:59

标签: javascript jquery html clone

我想在部分标题下克隆每个部分的bgimage而不影响原始图像。

这是我的HTML:

<div class="wrapper">
    <div class="section">
        <img class="bgimage" src="imagepath_1.jpg" alt="" />
        <h2>Title</h2>
        <!--clone goes here-->
    </div>
    <div class="section">
        <img class="bgimage" src="imagepath_2.jpg" alt="" />
        <h2>Title</h2>
        <!--clone goes here-->
    </div>
    <div class="section">
        <img class="bgimage" src="imagepath_3.jpg" alt="" />
        <h2>Title</h2>
        <!--clone goes here-->
    </div>
</div>

我的代码:

$(document).ready(function($) {
    $('.section').each( function (index, data) {    
        $(this).find('img.bgimage').first().clone().appendTo('.section h2').first();
    });
});

1 个答案:

答案 0 :(得分:1)

代码中的一个问题是appendTo将一个子元素添加到容器中。你真正想要的是insertAfter

另一个问题是您没有引用each功能中的每个部分。您应该使用第二个函数参数。

这是一个解决方案:

&#13;
&#13;
$(document).ready(function($) {
  $('.section').each(function (index, section) {    
    var image = $(section).find('img.bgimage').first(),
        title = $(section).find('h2').first();
    image.clone().insertAfter(title);
  });
});
&#13;
.section {
  border: 1px solid #888;
  margin: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div class="section">
        <img class="bgimage" src="http://api.jquery.com/jquery-wp-content/themes/jquery/images/logo-jquery.png" alt="" />
        <h2>Section 1</h2>
        <!--clone goes here-->
    </div>
    <div class="section">
        <img class="bgimage" src="http://jquery.com/jquery-wp-content/themes/jquery.com/i/feature-sprites.png" alt="" />
        <h2>Section 2</h2>
        <!--clone goes here-->
    </div>
    <div class="section">
        <img class="bgimage" src="http://jquery.com/jquery-wp-content/themes/jquery/images/jq-nav-icons.png" alt="" />
        <h2>Section 3</h2>
        <!--clone goes here-->
    </div>
</div>
&#13;
&#13;
&#13;

相关问题