【问题标题】:Duplicating an image in each container during iteration在迭代期间复制每个容器中的图像
【发布时间】:2015-11-10 17:03:13
【问题描述】:

我想在不影响原图的情况下,克隆每个部分的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();
    });
});

【问题讨论】:

    标签: javascript jquery html clone


    【解决方案1】:

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

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

    这里有一个解决方案:

    $(document).ready(function($) {
      $('.section').each(function (index, section) {    
        var image = $(section).find('img.bgimage').first(),
            title = $(section).find('h2').first();
        image.clone().insertAfter(title);
      });
    });
    .section {
      border: 1px solid #888;
      margin: 10px;
    }
    <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>

    【讨论】:

    • 没问题。请按下按钮接受我的回答(如果您还没有投票,也请点赞)。
    猜你喜欢
    • 2016-06-30
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多