简体   繁体   English

每次添加时,jQuery clone()将div加倍

[英]jQuery clone() doubling div each time it's appended

I'm currently working with the Tumblr API and trying to append each post. 我目前正在使用Tumblr API,并尝试附加每个帖子。 I would like to keep the caption and date published with the photo so I'm attempting to use the clone() method. 我想将标题和日期与照片一起发布,以便尝试使用clone()方法。 Every time a post is appended it doubles. 每次附加一个帖子,它都会加倍。 So the first post is one photo, the second is two of the same photo, third is four of the same photo, etc. 因此,第一条是一张照片,第二条是同一张照片中的两张,第三条是同一张照片中的四张,依此类推。

here's the HTML: 这是HTML:

<section class='site-content'>
    <span class="fa fa-bars"></span>
        <div class="tumblr">
            <div class="blog_content">
                <div class="blog_text">
                    <p class="date"></p>
                    <p class="caption"></p>
                </div>
                <div class="blog_media">    
                    <img class="blog_photo" src="" />
                    <div class="blog_video">
                    </div>
                </div>
            </div>
        </div>      
</section>

here is a code snippet: 这是一个代码片段:

for (var i = 0; i < 10; i++) {

    var type = results.response.posts[i].type;

    if (type === 'photo') {
    var photo = $('.blog_content').clone(); 
    photo.find('.caption').html(results.response.posts[i].caption); 
    photo.find('.date').text(results.response.posts[i].date);
    photo.find('.blog_photo').attr('src', results.response.posts[i].photos[0].original_size.url);
    $('.tumblr').append(photo);
    }

Can anybody spot where I'm making my mistake? 有人可以发现我在犯错吗?

You're running $('.blog_content').clone() in the loop repeatedly, which selects $('.blog_content') every time you run it and .clone() will return an array of all selected elements. 您在循环中反复运行$('.blog_content').clone() ,每次运行时都会选择$('.blog_content') .clone()将返回所有选定元素的数组。

Since this cloned set is then appended back, the selector will then clone 2, then 4, ... until the for loop terminates because that's how the DOM is structured at the time the selector is run. 由于此克隆集随后被附加回去,因此选择器将随后克隆2,然后是4 ...,直到for循环终止,因为这是运行选择器时DOM的结构。

You will need to either cache the value of the cloned DOM element outside of the loop or make your selector more specific to only return one element at a time. 您将需要在循环之外缓存克隆的DOM元素的值,或者使选择器更加具体,一次只返回一个元素。

使用.first()获取.blog_content类型的第一个并将其克隆

var photo =$('.blog_content').first().clone();

尝试这个

$('.blog_content').first().clone();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM