使用本地存储刷新页面后如何保存用户输入

时间:2021-01-22 17:16:54

标签: javascript jquery

我已经为此苦苦挣扎了一段时间。我有几个带有每小时时段的块,我想确保每次用户输入内容并单击保存按钮时,它已保存,即使刷新页面后它仍然保留在页面上,直到他们决定删除所写内容并输入内容那个盒子里的新东西。下面是我的 html 代码,只是为了让您知道我只是在学习 JS,因此我们将不胜感激。

let time = [];
const addText = (ev) => {
  let newTime = {
    timeData: document.querySelectorAll("#hour Block, #hourBlock1, #hourBlock2").value,

    textData: document.querySelector('.text-input').value
  }
  time.push(newTime);
  localStorage.setItem('My Time', JSON.stringify(time));
}

document.querySelector('.saveButton').addEventListener('click', addText);

document.querySelector('.text-input').value = localStorage.getItem('addText');
<div id="hourblock">
  <div id>9A M</div>
  <input data-hour="9" class="text-input" placeholder=""></inputs>
  <button class="saveButton"><i class="far fa-save fa-2x"></i></button>
</div>
<div id="hourBlock1">
  <div id>10AM</div>
  <input data-hour="10" class="text-input" placeholder=""></inputs>
  <button class="saveButton">
                          <i class="far fa-save fa-2x"></i>   
                        </button>
</div>
<div id="hourBlock2">
  <div id>11AM</div>
  <input data-hour="11" class="text-input" placeholder=""></inputs>
  <button class="saveButton">
                          <i class="far fa-save fa-2x"></i>   
                        </button>
</div>

3 个答案:

答案 0 :(得分:0)

我不认为您可以在刷新页面(使用 javascript)和脚本中的变量后保留数据。 “这可以通过 window.localStorage 或 window.sessionStorage 实现。不同之处在于 sessionStorage 只要浏览器保持打开状态就会持续存在,localStorage 在浏览器重新启动后仍然存在。持久性适用于整个网站,而不仅仅是它的单个页面。 ”在此问题中:https://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh#:~:text=This%20is%20possible%20with%20window,localStorage%20or%20window.&text=The%20difference%20is%20that%20sessionStorage,a%20single%20page%20of%20it

关于点击按钮的问题,你可以使用 onClick="yourFunction()" 像这样:

<button class="saveButton" onclick="addText()">
                <i class="far fa-save fa-2x"></i>   
</button>

答案 1 :(得分:0)

正如您标记了 jQuery,这里是 jQuery 中的解决方案。如果您不使用 jQuery,请随时移植它。

本质上,向您要保留的元素添加一个类,然后它将遍历每个元素并获取该项目的当前值,在更改/输入时将保存到 localStorage。< /p>

// iterate over .keep elements, attach storage event, update value if already in storage
$(document)
  .find('.keep')
  .each(function () {
    var elm = $(this);
    var data = JSON.parse(window.localStorage.getItem('input-' + elm.attr('id')));

    if (data && data.value !== null) {
      if (data.type === 'checkbox') {
        $('#' + elm.attr('id')).attr('checked', data.value);
      } else {
        $('#' + elm.attr('id')).val(data.value);
      }
    }

    $(window).on('storage', function (e) {
      if (data) $('#' + elm.attr('id'))[data.type === 'checkbox' ? 'checked' : 'val'](
        window.localStorage.getItem('input-' + elm.attr('id'))
      );
    });
  });

// on .storage change, store value
function store() {
  var elm = $(this);
  let data = {
    type: elm.attr('type') === 'checkbox' ? 'checkbox' : 'input',
    value: elm.attr('type') === 'checkbox' ? elm[0].checked : elm.val()
  }
  window.localStorage.setItem('input-' + elm.attr('id'), JSON.stringify(data));
}

// clear stored items, not efecting other potential keys
function clear() {
  for (var key in window.localStorage) {
    if (key.indexOf('input-') !== -1) {
      let data = JSON.parse(window.localStorage.getItem(key))

      // remove key from storage
      window.localStorage.removeItem(key);

      // clear local element
       if (data.type === 'checkbox') {
        $('#' + key.substring('input-'.length)).prop('checked', false);
      } else {
        $('#' + key.substring('input-'.length)).val('');
      }
    }
  }
}

$(document).on('keyup blur propertychange paste', '.keep', store);
$(document).on('change', 'select.keep', store);
$(document).on('change', 'input[type="checkbox"].keep', store);
$(document).on('click', '.clearkeep', clear);
<input class="keep" id="an-input" />

<select class="keep" id="a-select">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<input type="checkbox" class="keep" id="a-checkbox"/>

<button class="clearkeep">clearkeep</button>

在这里查看它的工作原理:https://playcode.io/716777/

答案 2 :(得分:0)

您的代码中有许多“理解”错误。我一一评论。

// This array should be declared inside the addText function.
// Else, everytimes the user saves, the array will grow...
// And it will end in more data than the amount of inputs.
let time = [];
const addText = (ev) => {
  let newTime = {

    // Here, the targetted elements are divs. There is no value to a div.
    timeData: document.querySelectorAll("#hour Block, #hourBlock1, #hourBlock2").value,

    // Here, you will get a value... 
    // But always the value of the first .text-input of the page.
    textData: document.querySelector('.text-input').value
  }
  time.push(newTime);
  localStorage.setItem('My Time', JSON.stringify(time));
}

// The event handler is setted only for the first button.
document.querySelector('.saveButton').addEventListener('click', addText);

// The first .text-input value will be setted to "null"
// Because there is no "addText" item in localStorage.
// You saved under the item named "My time".
document.querySelector('.text-input').value = localStorage.getItem('addText');

所以这是一个有效的代码。仔细查看差异。

const addText = (ev) => {
  let time = [];

  let fields = document.querySelectorAll(
    "#hourblock, #hourBlock1, #hourBlock2"
  );
  fields.forEach(function (element) {
    time.push({
      field: element.id,
      text: element.querySelector(".text-input").value
    });
  });
  console.log(time);
  localStorage.setItem("timeData", JSON.stringify(time));
};

document.querySelectorAll(".saveButton").forEach(function (btn) {
  btn.addEventListener("click", addText);
});

// on page load
let stored = JSON.parse(localStorage.getItem("timeData"));
if (stored) {
  console.log(stored);
  stored.forEach(function (item) {
    document
      .querySelector("#" + item.field)
      .querySelector(".text-input").value = item.text;
  });
}

这在 CodePen 中有效。