简体   繁体   中英

Javascript/Jquery: issue with append in cycle

I get Flickr gallery via API/Json. My issue with my code is that the gallery that I fetch has ~ 30 picture, but this snippet:

$.each(data.album.content,function (index,content)
        {
            album_container.append(column);
         [...]
}

Appends only one <div> to the container, and not 30, but appends in right way 30 a/img to this unique column . I cannot figure why and how solve it.

Thank you for your help!

var album_container = $('div#album');

function callGetAjax(url)
{
    return $.get(url,{});
}    

function getAlbum(feed_url)
{
    callGetAjax(absolute_path+'/feed/'+feed_url)
    .success(function(data)
    {
    })
    .error(function(xhr, statusText)
    {//console.log(statusText);
    })
    .done(function(data)
    {
        var loaded = 0;
        album_title = data.album.album_title;
        $('h1#gallery-title').html(album_title);
        var column  = $('<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2"></div>');
        $.each(data.album.content,function (index,content)
        {
            album_container.append(column);
            $('<a/>')
                .append($('<img class="img-responsive">').prop('src', content.photo))
                .prop('href', content.target)
                .prop('title', content.title)
                .attr('data-gallery', '')
                .appendTo(column)
                .colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});
        });


    }); 
}

Current HTML result:

<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
 <a href=".."><img src="..." /></a>
 <a href=".."><img src="..." /></a>
 <a href=".."><img src="..." /></a>
 [...]
</div>

HTML that I need:

<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
     <a href=".."><img src="..." /></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
     <a href=".."><img src="..." /></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2">
     <a href=".."><img src="..." /></a>
</div>

[...]

Remember that .append() will move the HTML node around the DOM tree when the node already exists in your document. In your case, you have declared:

var column  = $('<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2"></div>')

outside of your $.each() loop, therefore causing it to be repeatedly moved around inside album_container , instead of being cloned as you have expected. Therefore, what you would do is to declare it within your loop, such that the instance is not outside the scope of your loop:

var album_container = $('div#album');

function callGetAjax(url)
{
    return $.get(url,{});
}    

function getAlbum(feed_url)
{
    callGetAjax(absolute_path+'/feed/'+feed_url)
    .success(function(data)
    {
    })
    .error(function(xhr, statusText)
    {//console.log(statusText);
    })
    .done(function(data)
    {
        var loaded = 0;
        album_title = data.album.album_title;
        $('h1#gallery-title').html(album_title);

        $.each(data.album.content,function (index,content)
        {
            // Creates a new column for every image element
            var column  = $('<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2"></div>'),
                item = $('<a/>')
                    .append($('<img class="img-responsive">').attr('src', content.photo))
                    .attr('href', content.target)
                    .attr('title', content.title)
                    .attr('data-gallery', '')
                    .appendTo(column)
                    .colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});

            // Append column instance to the album container
            album_container.append(column);

        });


    }); 
}

If you're also looking for a review of your code, may I suggest you transition away from the jqXHR.success() and jqXHR.error() methods? They have been deprecated in favour of the jqXHR.done() and jqXHR.fail() methods. Using promises, we have a backbone that looks like this:

var album_container = $('div#album');

function callGetAjax(url)
{
    return $.get(url,{});
}    

function getAlbum(feed_url)
{
    // Store returned promise from $.get() in a variable
    var ajaxCall = callGetAjax(absolute_path+'/feed/'+feed_url);

    // Now we listen to the promise
    ajaxCall
    .done(function(data) {

        var loaded = 0;
        album_title = data.album.album_title;
        $('h1#gallery-title').html(album_title);

        $.each(data.album.content,function (index,content)
        {

            var column  = $('<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2"></div>'),
                item = $('<a/>')
                    .append($('<img class="img-responsive">').attr('src', content.photo))
                    .attr({
                        'href': content.target,
                        'title': content.title,
                        'data-gallery': ''
                    })
                    .appendTo(column)
                    .colorbox({rel:'gallery', speed:0, maxWidth:'95%', maxHeight:'95%'});

            album_container.append(column);

        });


    })
     .fail(function(xhr, statusText) {
        // Log error
        // console.log(statusText);
    }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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