首页 > 解决方案 > 本地存储问题 > 我似乎无法完成这项工作

问题描述

问题:本地存储不存储数据。

我正在为我的训练营开发一个每日调度应用程序。我正在尝试使用本地存储将数据保存在应用程序上。但是,当我刷新时,数据消失了。我包含了我正在使用的代码。如果你能告诉我哪里出错了,请告诉我。

非常感谢!

干杯

// Background Color Set Function

// define row is time in 24 hour time format
const rows = document.getElementsByClassName("row");
let currentHour = parseInt(moment().format('H'));

// lets make sure we are getting expected output
console.log(currentHour);


Array.from(rows).forEach(row => {
  let
    rowIdString = row.id,
    rowHour;
  if (rowIdString) {
    rowHour = parseInt(rowIdString);
  }
  if (rowHour) {
    // Compares row id to current hour and sets color accordingly
    if (currentHour === rowHour) {
      setColor(row, "red");
    } else if ((currentHour < rowHour)) {
      setColor(row, "green");
    } else {
      setColor(row, "lightgrey");
    }
  }
});

function setColor(element, color) {
  element.style.backgroundColor = color;
}


var input = document.getElementById('textArea6').value;
localStorage.setItem('text6', input);

document.getElementById('textArea6').value = localStorage.getItem('text6');
body {
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  line-height: 1;
}

textarea {
  background: transparent;
  border: none;
  resize: none;
  color: #000000;
  border-left: 1px solid black;
  padding: 10px;
}

.jumbotron {
  text-align: center;
  background-color: transparent;
  color: black;
  border-radius: 0;
  border-bottom: 10px solid black;
}

.description {
  white-space: pre-wrap;
}

.time-block {
  text-align: center;
  border-radius: 15px;
}

.row {
  white-space: pre-wrap;
  height: 80px;
  border-top: 1px solid white;
  ;
}

.hour {
  background-color: #ffffff;
  color: #000000;
  border-top: 1px dashed #000000;
}

.past {
  background-color: #d3d3d3;
  color: white;
}

.present {
  background-color: #ff6961;
  color: white;
}

.future {
  background-color: #77dd77;
  color: white;
}

.saveBtn {
  border-left: 1px solid black;
  border-top-right-radius: 15px;
  border-bottom-right-radius: 15px;
  background-color: #06AED5;
  color: white;
}

.saveBtn i:hover {
  font-size: 20px;
  transition: all .3s ease-in-out;
}

.red {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-8">

标签: javascript

解决方案


问题是(在 HTML 之外)您在页面加载后立即将文本区域的值存储到 localStorage,您可能应该在单击按钮时存储它(onclick执行其回调函数时),这里是一个例子:

function setColor(element, color) {
  element.style.backgroundColor = color;
}

function save_data() {
  var input = document.getElementById('textArea6').value;
  localStorage.setItem('text6', input);
}

document.getElementById('textArea6').value = localStorage.getItem('text6');

现在,当页面被加载时, 的值#textArea6 <textarea>被设置为text6来自 的值localStorage,当save_data函数被执行时,这个文本区域的值被保存到localStorage相同的属性名下。


推荐阅读