#javascript #local-storage
#javascript #локальное хранилище
Вопрос:
У меня есть код для отображения птиц, изображений птиц и тегов. Существует опция для избранных определенных птиц с помощью кнопки избранного. Я хочу сохранить птиц, выбранных в качестве избранных, в localstorage, как мне это сделать? Когда я пытаюсь сохранить значение favBtn.value, оно ничего не отображает. Заранее спасибо.
РЕДАКТИРОВАТЬ: я также поделился своим HTML-кодом сейчас
window.addEventListener('load', init);
const cardsContainer = document.querySelector('#cards');
const aside = document.querySelector('#wrapper aside');
/*
array with birds
*/
const birds={
'Koolmees':{
src:'https://source.unsplash.com/1600x900/?koolmees',
tags:'rotterdam, koolmees, kleine vogel'
},
'Specht':{
src:'https://source.unsplash.com/1600x900/?specht',
tags:'specht, nijmegen, kleine vogel'
},
'kerkuil':{
src:'https://source.unsplash.com/1600x900/?snowowl',
tags:'uil, eindhoven, grote vogel, roofvogel'
}
};
/*
if there is no `figcaption` below the image it will add the caption and
assign the `tags` text which is assigned to the image as a dataset attribute
*/
const clickhandler=function(e){
let fig=e.target.parentNode.querySelector('figcaption');
if( fig==null ){
fig=document.createElement('figcaption');
fig.textContent=this.dataset.tags
e.target.parentNode.appendChild( fig );
}else{
e.target.parentNode.removeChild(fig)
}
aside.textContent=fig==null ? '' : this.dataset.tags;
}
/*
this function changes te color in the button
*/
function setColor(el, color) {
if (el.value == 0) {
el.style.backgroundColor = "#FFFFFF"
el.value = 1;
} else {
el.style.backgroundColor = "#7FFF00"
el.value = 0;
}
}
function init(){
document.getElementById('cards').querySelectorAll('.card').forEach( card => {
card.addEventListener('click',clickhandler );
});
}
/*
adding elements to cards
*/
function addCard(birdImage, birdName, birdTags){// now takes 3 arguments
let item = document.createElement('flex-item');
item.classList.add('card');
item.dataset.tags=birdTags; //assign the tags as a dataset atttribute
cardsContainer.appendChild(item)
let favBtn = document.createElement('button')
favBtn.innerText = '❤'
favBtn.value = 0
favBtn.setAttribute('onclick', 'setColor(this, "#101010")')
favBtn.classList.add('fav-btn')
item.appendChild(favBtn)
let img = document.createElement('img')
img.src = birdImage;
img.title=birdTags; // tags also assigned for the img title
item.appendChild(img)
let name = document.createElement('div')
name.innerText = birdName
item.appendChild(name)
}
/*
Using the `object.keys` method allows us to quickly
iterate through each sub-object. The `key` is the bird name.
*/
function addCards(){
Object.keys( birds ).forEach( key => {
let bird=birds[ key ];
addCard( bird.src, key, bird.tags )
})
}
addCards()
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="magazine zonder fetch">
<meta name="keywords" content="HTML, CSS, JavaScript">
<meta name="author" content="Micha van der Willigen">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/style.css">
<title>Bird magazine</title>
</head>
<body>
<div id='wrapper'>
<header><p1>Vogel magazine voor vogelspotters!</p1></header>
<main>
<p>
<!-- with these buttons you can set the website in full screen -->
<button class="start" id="startFull">Start fullscreen on the whole page</button>
<button id="exit">Exit fullscreen</button>
</p>
<!-- here the cards with the birds will be displayed -->
<flex-container id="cards">
</flex-container>
</main>
<aside>Click on a bird to display the tags!</aside>
<footer><p>Website door Micha van der Willigen</p></footer>
</div>
<script src="js/main.js"></script>
<script src="js/fullscreen.js"></script>
</body>
</html>
Комментарии:
1. можете ли вы также поделиться своим HTML-кодом?
2. @ArchanaAgivale Теперь я включил HTML в свой вопрос
3. Вы говорите, что пытаетесь сохранить
favBtn.value
, но я не могу найти такую строку, за исключениемfavBtn.setAttribute('onclick', 'setColor(this, "#101010")')
которой я бы рекомендовал заменить наaddEventListener()
call .4. Могу ли я использовать вызов addEventListener, чтобы узнать, какая кнопка была нажата?
Ответ №1:
Я бы использовал пару функций для загрузки и записи в локальное хранилище
const loadBird = () => {
if (localStorage['favouriteBird'])
// If a saved bird exists
savedBird = JSON.parse(localStorage['favouriteBird'])
else
// No saved birds
savedBird = {}
}
const saveBird = () => {
localStorage['favouriteBird'] = JSON.stringify(favouriteBird)
}
Для использования в вашем коде просто добавьте loadBird()
в функцию init, а также добавьте favouriteBird
переменную в верхней части вашего скрипта.
Всякий раз, когда обновляется избранная птица, просто вызывайте saveBird()
функцию
Просто измените имена переменных на любые, которые вы хотите, а также добавьте if
оператор, чтобы проверить, есть ли savedBird
null
или undefined
, и если это так, просто определите его как начальную птицу.
Комментарии:
1. Я бы рекомендовал использовать
localStorage.getItem()
иlocalStorage.setItem()
2. Спасибо за ваш ответ! Я пытался использовать ваши функции, но я все еще не знаю, как назначить избранных птиц переменной favoritebird. Я могу заставить кнопку менять цвет при нажатии, но мне также нужно знать, какая кнопка была нажата, например
3. В моем последнем проекте действительно была очень похожая проблема. Может быть, вы могли бы попробовать создать переменную где-нибудь в вашем скрипте, которая ссылается на выбранную птицу. Может быть, добавить прослушиватель событий для каждой кнопки, который изменил бы переменную на любую птицу, которой соответствует кнопка? И после нажатия кнопки он просто вызывает
saveBird
функцию.