如何在不使用JQuery,JSON或任何外部库的情况下使用JavaScript在会话存储中存

以下代码包含带有不同类型食物选项的复选框。


如果任务是将复选框存储到会话存储中,并在以后检索它们,那么如何使用JavaScript存储和检索复选框,而不使用JQuery,JSON或任何外部库?


"use strict";


function validate() {

  var result = true;

  var food = getFood();

  if (result) {

    saveFood(food)

  }

  return result;

}


function getFood() {

  var foodType = "unknown";

  var foodArray = document.getElementById("food").getElementsByTagName("input");

  for (var i = 0; i < foodArray.length; i++) {

    if (foodArray[i].checked) {

      foodType = foodArray[i].value;

    }

  }

  return foodType;

}


function storeFood(food) {

  sessionStorage.food = food;

}


function retrieveFood() {

  switch (sessionStorage.food) {

    case "Pizza":

      document.getElementById("pizza").checked = true;

        break;

    case "Hamburger":

      document.getElementById("hamburger").checked = true;

        break;

    case "Sandwich":

      document.getElementById("sandwich").checked = true;

        break;

  }

}


function init() {

  if (document.getElementById("food-page") != null) {

    retrieveFood();

    document.getElementById("food-form").onsubmit = validate;

  }

}


window.onload = init;

<body id"food-page">

  <form id="food-form" method="post" action="server">

    <fieldset id="food">

      <legend>Foods</legend>

      <p>

        <label for="pizza">Pizza</label>

        <input type="checkbox" id="pizza" class="food-choices" name="food-checkboxes" checked="checked" value="Pizza" required="required" />

        <label for="hamburger">Hamburger</label>

        <input type="checkbox" id="hamburger" class="food-choices" name="food-checkboxes" value="Hamburger" />

        <label for="sandwich">Sandwich</label>

        <input type="checkbox" id="sandwich" class="food-choices" name="food-checkboxes" value="Sandwich" />

      </p>

    </fieldset>

  </form>

</body>


catspeake
浏览 139回答 3
3回答

犯罪嫌疑人X

JSON不是库,而是一种表示法。花一些时间来阅读它。有一些编码方法。下面有一个简单的示例。获取所有检查的输入及其值:var result = Array.from(document.querySelectorAll('input[type=checkbox]:checked')).map(a => { return { id: a.getAttribute("id"), value: a.value }; });console.log(result);在本地存储中保存和从中检索:var resultInJson = JSON.stringify(result);console.log(resultInJson);localStorage.setItem("data", resultInJson);console.log(localStorage.getItem("data"));console.log(JSON.parse(localStorage.getItem("data")));

FFIVE

没有JSON注意事项的解决方案:const&nbsp; foodForm = document.querySelector('#food-form'),&nbsp; StorageName = 'myFoodStorage';foodForm.onchange=()=>{&nbsp; &nbsp; // = storeFood&nbsp; let CheckList = Array.from(foodForm.querySelectorAll('input[type=checkbox]')).map(a=>`${a.id}=${a.checked}`);&nbsp; sessionStorage.setItem(StorageName, CheckList.join(','));}window.onload=()=>{&nbsp; &nbsp;// = retrieveFood&nbsp; let CheckList = sessionStorage.getItem(StorageName)&nbsp; if (CheckList) {&nbsp; &nbsp; CheckList.split(',').forEach(e=>{&nbsp; &nbsp; &nbsp; let pair = e.split('=');&nbsp; &nbsp; &nbsp; document.getElementById('pair[0]').checked = pair[1] === 'true';&nbsp; &nbsp; })&nbsp; }}

慕运维8079593

如果要更高级的序列化,请使用此方法,它应适用于所有值为字符串的对象。用于sessionStorage.setItem('foods', serialize(foodStates))存储复选框的状态并用于对其parse(sessionStorage.getItem('foods'))进行重构"use strict";function sanitize(str) {&nbsp; //Split into char array, escape chars and put back together into string&nbsp; return str.split('').map(chr => sanitize.map[chr] || chr).join('')}function desanitize(str) {&nbsp; //Split into char array, escape chars and put back together into string&nbsp; return str.replace('\\:', ':').replace('\\;', ';').replace('\\\\', '\\')}sanitize.map = {&nbsp; '\\': '\\\\',&nbsp; ':': '\\:',&nbsp; ';': '\\;'}function serialize(obj) {&nbsp; var result = "";&nbsp; for(var prop in obj) {&nbsp; &nbsp; result += `${sanitize(prop)} :${sanitize(obj[prop])} ;`;&nbsp; }&nbsp; //Remove last ' ;'&nbsp; result = result.slice(0, -2);&nbsp; return result;}function parse(str) {&nbsp; var obj = {};&nbsp; for(var part of str.split(' ;')) {&nbsp; &nbsp; var [key, value] = part.split(' :')&nbsp; &nbsp; key = desanitize(key)&nbsp; &nbsp; value = desanitize(value)&nbsp; &nbsp; obj[key] = value;&nbsp; }&nbsp; return obj;}var orgObj = {pizza: "true", hamburger: "false", sandwich: "true"}console.log(orgObj)var encodedString = serialize(orgObj)console.log(encodedString)var newObj = parse(encodedString)console.log(newObj)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript