我尝试动态创建一个数组(items=[])并存储信息,以便数组中的所有对象都列在localstorage
中。但是我的jQuery for
循环不工作了?一切正常,除了我的代码,从for循环jQuery到localstorage
。我不确定我是否犯了某种类型的错别字或在循环中使用了错误的变量。
var shoppingFormEl = $('#shopping-form');
var shoppingListEl = $('#shopping-list');
// TODO: Create a function to handle the form submission event that captures the form's <input>` value and prints it to the `shoppingListEl` as a `<li>`
function handleFormSubmit(event) {
event.preventDefault();
var shoppingInput = $('input[name="shopping-input"]').val();
if (!shoppingInput) {
alert(`please enter a value in the input field`);
return;
}
var items = []
shoppingListEl.append(`<li> ${shoppingInput} </li>`);
$('input[name="shopping-input"]').val(''); // removes it from input textbox
// console.log(shoppingInput);
$.each(shoppingInput, function() {
items.push($(this).val());
});
localStorage.setItem("items", JSON.stringify(items)); /// try again with making the array so all items appear in localstorage not one at a time
//added to practice local storage
}
// TODO: Add an event listener to the `shoppingFormEl` to handle submission
shoppingFormEl.on("submit", handleFormSubmit);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>jQuery Shopping List</title>
<link rel="stylesheet" type="text/css" href="./assets/css/jass.css" />
<link rel="stylesheet" type="text/css" href="./assets/css/style.css" />
</head>
<body class="bg-dark text-light">
<main class="my-5 mx-auto">
<h1>Shopping List</h1>
<hr />
<h2>Add an item to the list.</h2>
<form id="shopping-form">
<input type="text" class="form-input w-100" id="shopping-input" name="shopping-input"
placeholder="Enter item name" />
<button class="btn btn-info">Add Item</button>
</form>
<ul id="shopping-list"></ul>
</main>
<!-- Added link to the jQuery library -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- Your JavaScript file -->
<script type="text/javascript" src="assets/js/script.js">
</script>
</body>
</html>
1条答案
按热度按时间zlwx9yxi1#
你的循环是在文本输入中输入的字符串上迭代,而不是
localStorage
,这没有多大意义,因为用户一次只输入一项,所以没有数组、集合或类似数组的对象可供循环(除了字符串中的字符,但这也不是你想要的)。我甚至不知道为什么你觉得你需要一个数组或一个循环在这里。您所需要做的就是将
ul
的HTML字符串内容存储到localStorage
中,然后在页面加载时将该字符串返回给DOM。下面的代码在Stack Overflow中由于沙箱化而无法工作,但在this Fiddle中可以工作。