jquery 我如何让我的for循环在本地存储中执行?

wj8zmpe1  于 2023-10-17  发布在  jQuery
关注(0)|答案(1)|浏览(108)

我尝试动态创建一个数组(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>
zlwx9yxi

zlwx9yxi1#

你的循环是在文本输入中输入的字符串上迭代,而不是localStorage,这没有多大意义,因为用户一次只输入一项,所以没有数组、集合或类似数组的对象可供循环(除了字符串中的字符,但这也不是你想要的)。
我甚至不知道为什么你觉得你需要一个数组或一个循环在这里。您所需要做的就是将ul的HTML字符串内容存储到localStorage中,然后在页面加载时将该字符串返回给DOM。
下面的代码在Stack Overflow中由于沙箱化而无法工作,但在this Fiddle中可以工作。

// Static element references should be gottten just once
// rather than every time the function runs. Also, best
// practice is to set your references to the element(s)
// and not properties of the element(s) so that if you
// need to get a second property value, you won't have
// to re-scan the DOM for the same element again.
const shoppingFormEl = $('#shopping-form');
const shoppingListEl = $('#shopping-list');
const shoppingInput = $('input[name="shopping-input"]');

$(function(){
  // this code runs when the DOM is ready so this is the place to
  // restore the list from localStorage
  shoppingListEl.html(localStorage.getItem("items"));
});
   
shoppingFormEl.on("submit", handleFormSubmit);
    
function handleFormSubmit(event) {
  event.preventDefault();
    
  if (!shoppingInput.val()) {
    alert(`please enter a value in the input field`);
    shoppingInput.focus();  // Put focus back into input    
    return;
  }

  // Don't pad the list item with spaces
  shoppingListEl.append(`<li>${shoppingInput.val()}</li>`);
  $("#shopping-input").val(''); // removes it from input textbox
  
  // No need for a loop, array, or JSON.stringify(). Just put the contents of the ul into localStorage
  localStorage.setItem("items", shoppingListEl.html());  
}
<!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>

  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script src="assets/js/script.js">
  </script>
</body>
</html>

相关问题