Как мне записать выведенные картинки в Local Storage и по каким данным?

//Метод Fetch
const btn = document.querySelector('.j-btn');

btn.addEventListener('click', () => {
  const page = +document.getElementById('page').value;
  const limit = +document.getElementById('limit').value;

  let s = document.getElementById('j-result');
  s.textContent = '';
  if (!(page >= 1 && page <= 10)) {
    s.textContent = 'Номер страницы вне диапазона от 1 до 10';
    return;
  } if (!(limit >= 1 && limit <= 10)) {
    s.textContent = 'Лимит вне диапазона от 1 до 10';
    return;
  }
  if (!(limit >= 1 && limit <= 10 && page >= 1 && page <= 10)) {
    s.textContent = 'Номер страницы и лимит вне диапазона от 1 до 10';
    return;
  }
  // Делаем запрос за данными
  var requestOptions = {
    redirect: 'follow'
  };

  fetch(`https://picsum.photos/v2/list?page=${page}&limit=${limit}`, requestOptions)
    .then(response => response.json())
    .then(result => {
      console.log(result);

    })
});

const btn = document.querySelector('.j-btn');
const resultNode = document.querySelector('.j-result');

btn.addEventListener('click', () => {
  const page = +document.getElementById('page').value;
  const limit = +document.getElementById('limit').value;

  let s = document.getElementById('j-result');
  s.textContent = '';
  if (!(limit >= 1 && limit <= 10 && page >= 1 && page <= 10)) {
    s.textContent = 'Номер страницы и лимит вне диапазона от 1 до 10';
    return;
  } else {
    useRequest(`https://picsum.photos/v2/list?page=${page}&limit=${limit}`, displayResult);
  }

  function useRequest(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);

    xhr.onload = function() {
      if (xhr.status != 200) {
        console.log('Статус ответа: ', xhr.status);
      } else {
        const result = JSON.parse(xhr.response);
        if (callback) {
          callback(result);
        }
      }
    };

    xhr.onerror = function() {
      console.log('Ошибка! Статус ответа: ', xhr.status);
    };

    xhr.send();
  };

  function displayResult(apiData) {
    let cards = '';
    apiData.forEach(item => {
      const cardBlock = `
            <div class="card">
              <img
                src="${item.download_url}"
                class="card-image"
              />
              <p>${item.author}</p>
            </div>
          `;
      cards = cards + cardBlock;
    });
    resultNode.innerHTML = cards;
  }
});
.result {
  display: flex;
  flex-wrap: wrap;
  width: 500px;
}

.card {
  width: 200px;
  margin: 20px;
}

.card-image {
  display: block;
  width: 200px;
  height: 150px;
}

.btn {
  padding: 0;
  background-color: transparent;
  border: none;
  outline: none;
  -webkit-tap-highlight-color: transparent;
  box-shadow: none;
  cursor: pointer;
  border-radius: 5px;
  margin: 5px 10px;
  padding: 10px 15px;
  font-size: 12px;
  line-height: 15px;
  text-transform: uppercase;
  color: white;
  background: #307570;
  transition: 0.3s;
}

.btn:hover {
  box-shadow: 0px 2px 8px 2px rgba(141, 150, 178, 0.3);
  transform: scale(1.05);
}

legend {
  max-width: 115px;
  margin: 0 auto;
  padding: 0 13px;
}

fieldset {
  border-radius: 8px;
}
<!DOCTYPE html>
<html lang="ru">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Task-4</title>
</head>

<body>
  <fieldset>
    <legend>Размер картинки</legend>
    <p> <label>Номер страницы</label> <br />
      <input id="page" class="text" size="20" placeholder="Введите число от 1 до 10">
    </p>
    <p> <label>Лимит</label> <br />
      <input id="limit" class="text" size="20" placeholder="Введите число от 1 до 10">
    </p>
    <p> <button class="btn j-btn">Запрос</button> </p>
  </fieldset>
  <div id="j-result"></div>
  <img id="result" />
  <div class="result j-result">Здесь будет результат запроса</div>

  <script src="task4.js"></script>
</body>

</html>


Ответы (1 шт):

Автор решения: ksa

Как вариант...

const btn = document.querySelector('.j-btn');
const resultNode = document.querySelector('.j-result');

document.addEventListener('DOMContentLoaded', _ => {
  let a = localStorage.getItem('data')
  try {
a = JSON.parse(a);
if (Array.isArray(a)) displayResult(a)
  } catch (e) {
console.log(e)
  }
})


btn.addEventListener('click', () => {
  const page = +document.getElementById('page').value;
  const limit = +document.getElementById('limit').value;

  let s = document.getElementById('j-result');
  s.textContent = '';
  if (!(limit >= 1 && limit <= 10 && page >= 1 && page <= 10)) {
s.textContent = 'Номер страницы и лимит вне диапазона от 1 до 10';
return;
  } else {
useRequest(`https://picsum.photos/v2/list?page=${page}&limit=${limit}`, displayResult);
  }

  function useRequest(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);

xhr.onload = function() {
  if (xhr.status != 200) {
    console.log('Статус ответа: ', xhr.status);
  } else {
    localStorage.setItem('data', xhr.response)
    const result = JSON.parse(xhr.response);
    if (callback) {
      callback(result);
    }
  }
};

xhr.onerror = function() {
  console.log('Ошибка! Статус ответа: ', xhr.status);
};

xhr.send();
  };

});
  function displayResult(apiData) {
let cards = '';
apiData.forEach(item => {
  const cardBlock = `
            <div class="card">
              <img
                src="${item.download_url}"
                class="card-image"
              />
              <p>${item.author}</p>
            </div>
          `;
  cards = cards + cardBlock;
});
resultNode.innerHTML = cards;
  }
.result {
  display: flex;
  flex-wrap: wrap;
  width: 500px;
}

.card {
  width: 200px;
  margin: 20px;
}

.card-image {
  display: block;
  width: 200px;
  height: 150px;
}

.btn {
  padding: 0;
  background-color: transparent;
  border: none;
  outline: none;
  -webkit-tap-highlight-color: transparent;
  box-shadow: none;
  cursor: pointer;
  border-radius: 5px;
  margin: 5px 10px;
  padding: 10px 15px;
  font-size: 12px;
  line-height: 15px;
  text-transform: uppercase;
  color: white;
  background: #307570;
  transition: 0.3s;
}

.btn:hover {
  box-shadow: 0px 2px 8px 2px rgba(141, 150, 178, 0.3);
  transform: scale(1.05);
}

legend {
  max-width: 115px;
  margin: 0 auto;
  padding: 0 13px;
}

fieldset {
  border-radius: 8px;
}
<!DOCTYPE html>
<html lang="ru">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Task-4</title>
</head>

<body>
  <fieldset>
    <legend>Размер картинки</legend>
    <p> <label>Номер страницы</label> <br />
      <input id="page" class="text" size="20" placeholder="Введите число от 1 до 10">
    </p>
    <p> <label>Лимит</label> <br />
      <input id="limit" class="text" size="20" placeholder="Введите число от 1 до 10">
    </p>
    <p> <button class="btn j-btn">Запрос</button> </p>
  </fieldset>
  <div id="j-result"></div>
  <img id="result" />
  <div class="result j-result">Здесь будет результат запроса</div>

  <script src="task4.js"></script>
</body>

</html>

→ Ссылка