我想在本地存储中存储一组对象,但我只能将一个对象存储到该数组中。所有新对象都会覆盖索引 0 中的前一个对象。
这是我的 JavaScript 代码:
class Track {
constructor (title, genre) {
this.title = title;
this.genre = genre;
this.id = new Date().getTime();
this.creation = new Date();
}
}
class TrackList {
constructor () {
this.tracks = [];
}
newTrack(track) {
this.tracks.push(track);
this.saveLocalStorage();
}
saveLocalStorage() {
localStorage.setItem('tracks', JSON.stringify(this.tracks));
}
}
const addSongForm = document.querySelector('.addSongForm');
addSongForm.addEventListener('submit', (e) => {
const songTitle = document.querySelector('.songTitle').value;
const songGenre = document.querySelector('.songGenre').value;
const newTrackForm = new Track(songTitle, songGenre);
const trackList = new TrackList();
trackList.newTrack(newTrackForm);
});
提前致谢!!
catspeake
相关分类