查看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对象文字将动态更改。那我怎么能让这个功能起作用呢?
太复杂了,但点击下面的链接并向下滚动到底部:
答案 0 :(得分:1)
localStorage.getItem('favoList')
为什么不使用地图代替数组?
同样@ fl9指出你的for循环永远不会开始!因为(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
})();
从0开始是
但我想在将笑话推入收藏列表之前检查重复项
根据定义,哈希不允许重复条目,因此无需担心重复
在this小提琴的控制台中运行 $mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPKeepAlive = true;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; // sets the prefix to the server
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port
$mail->Username = "membership@oiyc.org"; // GMAIL username
$mail->Password = "*******************"; // GMAIL password
$mail->isHTML(true); // send as HTML
$mail->WordWrap = 100; // set word wrap
$mail->Sender = "membership@oiyc.org";
$mail->addReplyTo($_SESSION['se-reply'],$_SESSION['se-from']);
$mail->setFrom($_SESSION['se-reply'],$_SESSION['se-from']);
$mail->DKIM_domain = "oiyc.org";
$mail->DKIM_private = "*********/rsa.private"; //path to file on the disk.
$mail->DKIM_selector = "mainkey";// change this to whatever you set during step 2
$mail->DKIM_passphrase = "";
$mail->DKIM_identity = $mail->Sender;
:
Delivered-To: ********@gmail.com
Received: by 10.46.25.85 with SMTP id p82csp1388830lje;
Sun, 4 Feb 2018 11:11:56 -0800 (PST)
X-Received: by 10.98.196.204 with SMTP id h73mr11556131pfk.143.1517771515865;
Sun, 04 Feb 2018 11:11:55 -0800 (PST)
ARC-Seal: i=1; a=rsa-sha256; t=1517771515; cv=none;
d=google.com; s=arc-20160816;
b=*****
qrIA==
ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
h=content-transfer-encoding:mime-version:list-unsubscribe:message-id
:subject:reply-to:to:date:from:dkim-signature
:arc-authentication-results;
bh=ptVvqh2PiSco0+Kb7wjBXHUijnbEm43LU4E+zStVvb0=;
b=********
iuTg==
ARC-Authentication-Results: i=1; mx.google.com;
dkim=pass header.i=@oiyc-org.20150623.gappssmtp.com header.s=20150623 header.b=ytsz7YWm;
spf=neutral (google.com: 209.85.220.41 is neither permitted nor denied by best guess record for domain of membership@oiyc.org) smtp.mailfrom=membership@oiyc.org
Return-Path: <membership@oiyc.org>
Received: from mail-sor-f41.google.com (mail-sor-f41.google.com. [209.85.220.41])
by mx.google.com with SMTPS id i3sor1037208pgs.91.2018.02.04.11.11.55
for <********@gmail.com>
(Google Transport Security);
Sun, 04 Feb 2018 11:11:55 -0800 (PST)
Received-SPF: neutral (google.com: 209.85.220.41 is neither permitted nor denied by best guess record for domain of membership@oiyc.org) client-ip=209.85.220.41;
Authentication-Results: mx.google.com;
dkim=pass header.i=@oiyc-org.20150623.gappssmtp.com header.s=20150623 header.b=ytsz7YWm;
spf=neutral (google.com: 209.85.220.41 is neither permitted nor denied by best guess record for domain of membership@oiyc.org) smtp.mailfrom=membership@oiyc.org
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=oiyc-org.20150623.gappssmtp.com; s=20150623;
h=from:date:to:reply-to:subject:message-id:list-unsubscribe
:mime-version:content-transfer-encoding;
bh=ptVvqh2PiSco0+Kb7wjBXHUijnbEm43LU4E+zStVvb0=;
b=*********
SsBA==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=1e100.net; s=20161025;
h=x-gm-message-state:from:date:to:reply-to:subject:message-id
:list-unsubscribe:mime-version:content-transfer-encoding;
bh=ptVvqh2PiSco0+Kb7wjBXHUijnbEm43LU4E+zStVvb0=;
b=*************
r+zA==
X-Gm-Message-State: AKwxytcQCxD/95gmJfS/DyCC4XOh8K3K+Jj9QONeHmVyCH5ebJDtxvIl tQwyBjpS9etVQopYODbtnZZ2Kw0k1Pc=
X-Google-Smtp-Source: AH8x227kdTn+9Ee7QoJFUYDPq/ax7LmKHzsDAtCNr/5cL0MidmAB3GWuEw4RU28Zb3jl8Kx0uAnegw==
X-Received: by 10.99.96.80 with SMTP id u77mr6305435pgb.401.1517771515191;
Sun, 04 Feb 2018 11:11:55 -0800 (PST)
Return-Path: <membership@oiyc.org>
Received: from oiyc.org ([2600:3c01::f03c:91ff:fe56:5129])
by smtp.gmail.com with ESMTPSA id m65sm14046167pfc.150.2018.02.04.11.11.54
for <********@gmail.com>
(version=TLS1 cipher=ECDHE-RSA-AES128-SHA bits=128/128);
Sun, 04 Feb 2018 11:11:54 -0800 (PST)
From: Bob Brunius <membership@oiyc.org>
X-Google-Original-From: Bob Brunius <********@gmail.com>
Date: Sun, 4 Feb 2018 11:11:53 -0800
To: ********@gmail.com
Reply-To: Bob Brunius <********@gmail.com>
Subject: A different sort of test 123d
Message-ID: <MR3sDgtyN4siuc2vYCZLxL34VuLFlexvK0WbbcEH7FA@oiyc.org>
X-Mailer: PHPMailer 6.0.3 (https://github.com/PHPMailer/PHPMailer)
List-Unsubscribe: <information@oiyc.org>, <https://oiyc.org/membershipDatabaseForms/unsubscribe.php?email=********@gmail.com&member=242>
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="b1_MR3sDgtyN4siuc2vYCZLxL34VuLFlexvK0WbbcEH7FA"
Content-Transfer-Encoding: 8bit
--b1_MR3sDgtyN4siuc2vYCZLxL34VuLFlexvK0WbbcEH7FA
Content-Type: text/plain; charset=us-ascii
Hello 12345678-abcd
--b1_MR3sDgtyN4siuc2vYCZLxL34VuLFlexvK0WbbcEH7FA
Content-Type: text/html; charset=us-ascii
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
Hello 12345678-abcd
</body>
</html>
--b1_MR3sDgtyN4siuc2vYCZLxL34VuLFlexvK0WbbcEH7FA--
答案 1 :(得分:1)
问题是for循环,它第一次执行收藏夹将是一个空数组,所以它的长度将为0,所以它永远不会进入循环
这样的事情应该有效:
favorites = favorites.filter(joke => joke.id !== norrisJoke.id).concat(norrisJoke);
答案 2 :(得分:1)
您正试图在此处运行一个空列表
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);
}