/
Coderdev
/
web-static-labs
Обзор
Документация
Войти
/
Coderdev
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
html/lab6/task5/script.js
62 строки
2 KB
Coderdev
1
12 май 2026, 12:37
12 май 2026, 12:37
d8ecd0f
Код
Авторство
О чём код?
const loadBtn = document.getElementById('load-btn'); const addFavBtn = document.getElementById('add-fav-btn'); const mainImg = document.getElementById('main-img'); const status = document.getElementById('status'); const favContainer = document.getElementById('favorites'); let currentImageUrl = ''; async function loadImage() { const type = document.querySelector('input[name="animal"]:checked').value; const url = type === 'dog' ? 'https://dog.ceo/api/breeds/image/random' : 'https://api.thecatapi.com/v1/images/search'; status.textContent = 'Загрузка...'; addFavBtn.disabled = true; try { const response = await fetch(url); if (!response.ok) throw new Error('Ошибка сети'); const data = await response.json(); currentImageUrl = type === 'dog' ? data.message : data[0].url; mainImg.src = currentImageUrl; status.textContent = ''; addFavBtn.disabled = false; } catch (err) { status.textContent = 'Не удалось загрузить картинку'; } } function saveToFavorites() { const favorites = JSON.parse(localStorage.getItem('fav_animals')) || []; const entry = { url: currentImageUrl, date: new Date().toLocaleString() }; favorites.push(entry); localStorage.setItem('fav_animals', JSON.stringify(favorites)); renderFavorites(); } function renderFavorites() { const favorites = JSON.parse(localStorage.getItem('fav_animals')) || []; favContainer.innerHTML = ''; favorites.forEach(item => { const div = document.createElement('div'); div.className = 'favorite-item'; div.innerHTML = ` <img src="${item.url}"> <p><small>${item.date}</small></p> `; favContainer.appendChild(div); }); } loadBtn.addEventListener('click', loadImage); addFavBtn.addEventListener('click', saveToFavorites); window.addEventListener('DOMContentLoaded', renderFavorites);