weixin_33749242 2015-07-14 06:14 采纳率: 0%
浏览 25

jQuery AJAX .each()没有停止

Not sure if the title makes sense but here's my problem;

I currently use Dropbox to share family photos, trying to put them all into an HTML page in their own DIV based on their content.

I load them via a JSON file that looks like this

[
    {
        "Birthday": "10"
    },
    {
        "Camping": "20"
    },
    {
        "July Fourth": "50"
    }
]

And using jQuery .ajax to load them

$(document).ready(function () {
  $.ajax({
    url: 'events.json',
    success: function(response) {
      $.each(response, function() {
        $.each(this, function(name, photos) {
          $('#container').append('<div class="gallery" name="' + name + '"></div>');
          $('div[name="' + name + '"').append(function() {
            for ( var i = 1; i <= photos; i++) {
              if (i < 10) {
                $('.gallery').append('<a class="fancybox" rel="' + this + '" href="' + name + '/0' + i + '.jpg"><img class="img" src="' + name + '/0' + i + '.jpg" /></a>');
              } else {
                $('.gallery').append('<a class="fancybox" rel="' + this + '" href="' + name + '/' + i +'.jpg"><img class="img" src="' + name + '/' + i + '.jpg" /></a>');
              }
            }
          });
        });
      });
    }
  });
  $(".fancybox").fancybox();
});

It creates each DIV that's needed, but instead of putting each in their own they stack

birthday contains "birthday, camping, july fourth"

camping contains "camping, july fourth"

july fourth contains itself

How do I go about making it not contain each category after it?

  • 写回答

2条回答 默认 最新

  • weixin_33726318 2015-07-14 08:36
    关注

    I've actually figured out how to fix this, it was quite simple and a total derp on my end

    I just changed the $('.gallery').append()s to $(this).append()

    Also, I know the JSON wasn't great, I have fixed that.

    $.getJSON("events.json", function(data) {
      $.each(data, function(index, d) {
        var name = d.name;
        var photos = d.count;
        $('#container').append('<div class="gallery" name="' + name + '"></div>');
        $('div[name="'+name+'"]').append(function() {
          for ( var i = 1; i <= photos; i++) {
            if (i < 10) {
              $(this).append('<a class="fancybox" rel="' + this + '" href="' + name + '/0' + i + '.jpg"><img class="img" src="' + name + '/0' + i + '.jpg" /></a>');
            } else {
              $(this).append('<a class="fancybox" rel="' + this + '" href="' + name + '/' + i +'.jpg"><img class="img" src="' + name + '/' + i + '.jpg" /></a>');
            }
          }
        });
      });
    });
    
    评论

报告相同问题?