应该选择重新加载页面图像

时间:2016-01-05 14:38:33

标签: javascript jquery css json

我需要存档的内容:

  • 使用选定的班级切换图像
  • 重新加载页面,应记住以前选择的图片。

我遇到的问题: myPhotos阵列没有选择每个' item ...它使用类'选择'循环元素。但每次都添加相同的一个。

第二个问题是需要更改displayPhotos功能,以便每次都显示所有图像。 但保留刷新时选择的那些

请帮忙。

我创造了一个小提琴,因为下面的代码不起作用。 https://jsfiddle.net/1mes2z6s/1/



// Creates an empty array for selected photos to be added to
myPhotos = [];

// ---------------------------------------------
// Callback function to get photos from flickr
// ---------------------------------------------
(function() {

  //changed the callback so that it is defined
  window.cb = function(data) {
    //user returned data 
    displayPhotos(data);
  }

  var tags = "london";
  var script = document.createElement('script');

  script.src = "https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=cb&tags=" + tags;
  document.head.appendChild(script);


})();

// ------------------------------------
// Display photos
// ------------------------------------
function displayPhotos(data) {
  var $images = $('#images');

  // Check if localStorage key is empty (e.g. no photos have previously been selected) and go and get some
  if (localStorage.getItem("mySavedPhotos") === null) {

    // loop through photos in the JSON endpoint
    for (var i = 0; i < data.items.length; i++) {
      $('<img/>').attr('src', data.items[i].media.m).appendTo($images);
    }

    // localStorage key has items, so show them instead    
  } else {

    // retrive the items in localStorage
    var len = JSON.parse(localStorage['mySavedPhotos']).length
    var item = JSON.parse(localStorage['mySavedPhotos'])

    // loop through photos in local storage
    for (var i = 0; i < len; i++) {
      $('<img/>').attr('src', item[i]).appendTo($images);
    }
  }
}

// ------------------------------------
// Add 'selected' class to photo, push it to the 'myPhotos' array, then add array to localStorage
// ------------------------------------
function selectPhoto(photo) {


  // add 'selected' class to image
  photo.addClass('selected');

  // push the 'src' of that image to the array
  myPhotos.push(photo.attr('src'));

  var mySavedPhotos = myPhotos;

  // JSON stingify the items in local storage so they can be accessed easily
  localStorage['mySavedPhotos'] = JSON.stringify(mySavedPhotos);

  // debug
  // console.log(JSON.parse(localStorage['mySavedPhotos']));

}

// ------------------------------------
// JQUERY DOM LOADED
// ------------------------------------
$(function() {

  // When user clicks on photo to select
  $('#images').on('click', 'img', function() {

    selectPhoto($(this));

  });

  // Clear the local storage items (for debug)
  $('#debugBtn').on('click', 'button', function() {
    localStorage.removeItem("mySavedPhotos");
    console.log(localStorage);
  });

});
&#13;
			div#images img {
			  width: 100px;
			  height: 100px;
			  margin: 10px;
			  border: 3px solid #fff;
			}
			div#images img.selected {
			  border: 3px solid #f06;
			}
			
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- this is where the photos will be displayed -->
<div id="images"></div>

<!-- this is a button to clear localStorage items and is for debugging -->
<div id="debugBtn">
  <button>Remove LocalStorage Key</button>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

如果我理解正确,我认为你想要这样的东西:

function displayPhotos(data) {
    var $images = $('#images');
    var savedPhotos = []; // default to empty array
    var localPhotos = localStorage.getItem("mySavedPhotos");

    if (localPhotos) {
        savedPhotos = JSON.parse(localPhotos);
    }

    // loop through photos in the JSON endpoint
    for (var i = 0; i < data.items.length; i++) {
        var src = data.items[i].media.m;
        var $img = $('<img/>').attr('src', src);
        // add selected class if it is in our storage array
        if ($.inArray(src, savedPhotos) !== -1) {
            $img.addClass('selected')
        }
        $img.appendTo($images);
    }   

}

DEMO

答案 1 :(得分:1)

我认为这就是你想要的,看看这个有效的解决方案here

<强> HTML

<!-- this is where the photos will be displayed -->
<div id="images"></div>

<!-- this is a button to clear localStorage items and is for debugging -->
<div id="debugBtn">
  <button>Remove LocalStorage Key</button>
</div>

<强> Jquery的

// Creates an empty array for selected photos to be added to
myPhotos = [];
if (localStorage['mySavedPhotos'])
  myPhotos = JSON.parse(localStorage['mySavedPhotos']);

// ---------------------------------------------
// Callback function to get photos from flickr
// ---------------------------------------------
(function() {

  //changed the callback so that it is defined
  window.cb = function(data) {
    //user returned data 
    displayPhotos(data);
  }

  var tags = "london";
  var script = document.createElement('script');

  script.src = "https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=cb&tags=" + tags;
  document.head.appendChild(script);


})();

// ------------------------------------
// Display photos
// ------------------------------------
function displayPhotos(data) {
  var $images = $('#images');

  // Check if localStorage key is empty (e.g. no photos have previously been selected) and go and get some
  if (localStorage.getItem("mySavedPhotos") === null) {

    // loop through photos in the JSON endpoint
    for (var i = 0; i < data.items.length; i++) {
      $('<img/>').attr('src', data.items[i].media.m).appendTo($images);
    }

    // localStorage key has items, so show them instead    
  } else {

    // retrive the items in localStorage
    var len = JSON.parse(localStorage['mySavedPhotos']).length
    var item = JSON.parse(localStorage['mySavedPhotos'])
    for (var i = 0; i < data.items.length; i++) {
      // loop through photos in local storage
      //console.log($.inArray(data.items[i].media.m, item));
      if ($.inArray(data.items[i].media.m, item) >= 0) {
        $('<img/>').attr('src', data.items[i].media.m).addClass('selected').appendTo($images);
      } else {
        $('<img/>').attr('src', data.items[i].media.m).appendTo($images);
      }
    }

    //console.log(JSON.parse(localStorage['mySavedPhotos']));
  }
}

// ------------------------------------
// Add 'selected' class to photo, push it to the 'myPhotos' array, then add array to localStorage
// ------------------------------------
function selectPhoto(photo) {

  if (photo.hasClass('selected')) {
    photo.removeClass('selected');
    myPhotos = jQuery.grep(myPhotos, function(value) {
      return value != photo.attr('src');
    });
    localStorage['mySavedPhotos'] = JSON.stringify(myPhotos);
  } else {
    // add 'selected' class to image
    photo.addClass('selected');

    // push the 'src' of that image to the array
    myPhotos.push(photo.attr('src'));

    var mySavedPhotos = myPhotos;

    // JSON stingify the items in local storage so they can be accessed easily
    localStorage['mySavedPhotos'] = JSON.stringify(mySavedPhotos);

    // debug
    // console.log(JSON.parse(localStorage['mySavedPhotos']));
  }
}

// ------------------------------------
// JQUERY DOM LOADED
// ------------------------------------
$(function() {

  // When user clicks on photo to select
  $('#images').on('click', 'img', function() {

    selectPhoto($(this));

  });

  // Clear the local storage items (for debug)
  $('#debugBtn').on('click', 'button', function() {
    localStorage.removeItem("mySavedPhotos");
    console.log(localStorage);
  });

});

你正在做的是myPhotos = [];,之后被分配到localStorage这就是为什么每次刷新新数据都会被使用而旧的数据丢失