gpt4 book ai didi

javascript - 如何遍历所有 id?

转载 作者:行者123 更新时间:2023-11-28 17:38:08 24 4
gpt4 key购买 nike

查看 API --> https://api.icndb.com/jokes/random/10

每次用户点击特定笑话时,它都会被添加到收藏列表中。

为了保持代码简洁,我将仅显示函数本身:

 (function() {
"use strict";

const getJokesButton = document.getElementById('getData');
getJokesButton.addEventListener('click', getData);

loadLocalStorage();

function loadLocalStorage() {
let storage = JSON.parse(localStorage.getItem('favoList')) || [];
let listOfFavorites = document.getElementById("favorites");
let emptyArray = '';
if(storage.length > 0) {
for(let i = 0; i < storage.length; i++) {
let idNumberJoke = storage[i].id;
emptyArray +=
`<li><input type="checkbox" id='${idNumberJoke}'/> User title: ${storage[i].joke}</li>`;
listOfFavorites.innerHTML = emptyArray;
}
} else {
return false;
}
}

// fetch data from api
function getData() {
let listOfJokes = document.getElementById("list-of-jokes");

fetch('https://api.icndb.com/jokes/random/10')
.then(function(res) {
return res.json();
}).then(function(data) {
// variable is undefined because it is not initialized. Therefore at some empty single quotes
let result = '';
console.log(data.value);
data.value.forEach((joke) => {
result +=
`<li><input type="checkbox" class='inputCheckbox' id='${joke.id}'/> User title : ${joke.joke}</li>`;
listOfJokes.innerHTML = result;
});
bindCheckbox();
}).catch(function(err) {
console.log(err);
});
}

function clickedButton() {
getJokesButton.setAttribute('disabled', 'disabled');
getJokesButton.classList.add('opacity');
}

function bindCheckbox() {
let inputCheckbox = document.querySelectorAll('input[type=checkbox]');
let elems = document.getElementById('list-of-jokes').childNodes;
let favoriteList = document.getElementById('favorites');
let fav = JSON.parse(localStorage.getItem('favoList'))|| [];

if(elems.length > 0) {
inputCheckbox.forEach(function(element, index) {
inputCheckbox[index].addEventListener('change', function() {
let joke = this;
if(joke.checked && joke.parentNode.parentNode.id === 'list-of-jokes') {
joke.checked = false;
favoriteList.appendChild(joke.parentNode);
addFavorite(joke.id, joke.parentNode.innerText, fav);
}
if(joke.checked && joke.parentNode.parentNode.id === 'favorites') {
joke.checked = false;
removeFavorite(joke, index);
}
});
});
}
clickedButton();
}

function removeFavorite(favorite, index) {
let favoriteCheckBox = favorite;
let i = index;

// convert iterable object to an array, otherwise splice method would give an error.
let favoriteListItem = Array.from(favoriteCheckBox.parentNode);
favoriteListItem.splice(i, 1);
document.getElementById('list-of-jokes').appendChild(favorite.parentNode);
localStorage.setItem('favoList', JSON.stringify(favoriteListItem));
}

// store favorites in localStorage
function addFavorite(jokeId, jokeText, fav) {
let norrisJoke = {
id: jokeId,
joke: jokeText
};
let favorites = fav;

for (let i = 0; i < favorites.length; i++) {
if(favorites[i].id !== norrisJoke.id) {
favorites.push(norrisJoke);
}
}
// favorites[i].id !== norrisJoke.id

// always get the object before the push method and pass it into stringify
localStorage.setItem('favoList', JSON.stringify(favorites));
}

// function which will randomly add one joke to favorite list every 5 seconds
// function need a button which allows you to turn on and off this auto add function
})();
<div class="inner-body">
<button id="getData">GET Jokes</button>

<div class='inner-block'>
<h2>Chuck Norris Jokes</h2>

<ul class='unordered-list' id="list-of-jokes">
</ul>
</div>

<div class='inner-block'>
<h2>Favorites</h2>
<ul class='unordered-list' id="favorites">
</ul>
</div>
</div>

键和值不会被推送到 localStorage 中,我唯一看到的是 localStorage 中的空 [] 。 norrisJoke 对象文字将动态更改。那么我怎样才能让这个功能发挥作用呢?

太复杂,但点击下面的链接并向下滚动到底部:

https://codepen.io/chichichi/pen/Gyzzvb

最佳答案

您正在尝试浏览此处的空列表

for (let i = 0; i < favorites.length; i++) {
if(favorites[i].id !== norrisJoke.id) {
favorites.push(norrisJoke);
}
}

这意味着不会推送任何内容。您可以将列表缩减为 id 数组,然后检查该笑话是否存在于列表中。

const favIds = favorites.reduce((sum, element) => { 
return sum.concat(element.id);
},
[]);

现在您可以检查收藏夹中是否不存在该笑话

if(!favIds.includes(jokeId)){
favorites.push(norrisJoke);
}

关于javascript - 如何遍历所有 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com