Images appending twice in Jquery

时间:2015-08-14 22:49:07

标签: javascript jquery

This is probably just a dumb mistake I'm making but I'm having a problem with this event handler

$('.instagram').on('didLoadInstagram', function(event, response)

running twice so my images get appended twice. I know its running twice because I checked it with a print statement. Here is the full function in my code:

$('button').click(function(){
    jQuery(function($) {
      $("#pictures").html("");
      $('.instagram').on('willLoadInstagram', function(event, options) {
        console.log(options);
      });
      $('.instagram').on('didLoadInstagram', function(event, response) {
        console.log(response)
        console.log("go")
        for (i = 0; i < response.data.length; i++) {
            var DOM_img = document.createElement("img");
            var link = document.createElement('a'); 
            DOM_img.setAttribute('src', response.data[i].images.thumbnail.url);
            link.setAttribute('href', response.data[i].link);
            link.appendChild(DOM_img)
            pictures.appendChild(link);
        }

      });
      $('.instagram').instagram({
        search: {
        lat: lat,
        lng: lng,
        distance: document.getElementById('Distance').value
      },
        count : 33,
        clientId: 'removed'
      });
    });
});

Whats happening is that when you click the button the it will print out an extra div 'pictures' for each time youve clicked the button. So, the first will give one set, the second will give the set then give its duplicate, and the third will give the set then two duplicates.

Thanks for any help on this

1 个答案:

答案 0 :(得分:1)

正如Stryner正确地注意到你在$('.instagram')对象上附加了多个事件处理程序。您应该只在按钮单击事件处理程序中移动instagram函数调用,并将所有其他内容保留在外部。

示例:

jQuery(function($) {
  $("#pictures").html("");
  $('.instagram').on('willLoadInstagram', function(event, options) {
    console.log(options);
  });
  $('.instagram').on('didLoadInstagram', function(event, response) {
    console.log(response)
    console.log("go")
    for (i = 0; i < response.data.length; i++) {
      var DOM_img = document.createElement("img");
      var link = document.createElement('a'); 
      DOM_img.setAttribute('src', response.data[i].images.thumbnail.url);
      link.setAttribute('href', response.data[i].link);
      link.appendChild(DOM_img)
      pictures.appendChild(link);
    }
  });
  $('button').click(function(){
    $('.instagram').instagram({
      search: {
        lat: lat,
        lng: lng,
        distance: document.getElementById('Distance').value
      },
      count : 33,
      clientId: 'removed'
    });
  });
});