更改对象类并保存,这是`localstorage`中的更改

时间:2019-02-21 04:37:49

标签: javascript switch-statement local-storage

我有数百个按钮。页面加载时,这些按钮上会附加一个星号。该星标会通过点击该星标来指示最喜欢或不喜欢的那个星标。

我希望在单击该星时将其更改为“收藏”星,然后在再次单击时将其更改为“取消收藏”,依此类推。然后,保存在本地存储中。现在,它不会切换。而是更改按钮的类别而不是最喜欢的星星。

如何解决这个问题?

此外,该按钮在被收藏时也将被带到列表的顶部,因此它更加可见。

我已从以下代码开始:

// give buttons a star and give it a unique ID for changing
var img = new Image();
var buttons = [...document.getElementsByClassName('myButton')];
img.src = 'icons/buttons/fav.png';

img.onload = function () {
    buttons.forEach(button => {
        img.id = button.id + 'butfav';
        button.innerHTML += img.outerHTML;
    });
};
img.classList.add('fav');
img.setAttribute("href", "#");
img.setAttribute("title", "Favorite");

// favorite  code

// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
  document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.myButtons').addEventListener('click', function(e) {
  var id = e.target.id,
      item = e.target,
      index = favorites.indexOf(id);
  // return if target doesn't have an id (shouldn't happen)
  if (!id) return;
  // item is not favorite
  if (index == -1) {
    favorites.push(id);
    item.className = 'unfav';
  // item is already favorite
  } else {
    favorites.splice(index, 1);
    item.className = 'fav';
  }
  // store array in local storage
  localStorage.setItem('favorites', JSON.stringify(favorites));
});

// local storage stores strings so we use JSON to stringify for storage and 
parse to get out of storage
.myButton {
    position: relative;
    background-color: rgba(0,0,0,.7);
    font-family: 'coda';
    width: 45.5%;
    margin-right: 2px;
    margin-bottom: 9px;
    padding: 10px;
    padding-top: 8px;
    padding-bottom: 8px;
    display: inline-block;
    text-align: center;
    vertical-align: middle;
    font-weight: bold;
    cursor: pointer;
    color: #FFFFFF;
    box-shadow: 0 5px grey;
    font-size: 16px;
    border-radius: 6px;
    border: solid #FFFFFF 2px;
    text-decoration: none;
    transition: .2s;
}
.fav {
    all: initial;
    height: 24px;
    width: 24px;
    right: 0px;
    position: absolute;
    cursor: pointer;
    z-index: +20;
}
.unfav {
    all: initial;
    height: 24px;
    width: 24px;
    right: 0px;
    position: absolute;
    cursor: pointer;
    content:url("icons/buttons/unfav.png")
}
<div class="container" id="buttons">
<div id="container">
<div id="musicmemes" class="music_container">
<span><a href="#" class="myButton" id="sound1">Sound 1</a></span>
<span><a href="#" class="myButton" id="sound2">Sound 2</a></span>
<span><a href="#" class="myButton" id="sound3">Sound 3</a></span>
</div>
</div>
</div>

0 个答案:

没有答案