一个本地存储JavaScript,用于不同页面上的字段

时间:2017-09-30 08:02:21

标签: javascript local-storage

三个不同的网页各有三个可疑区域(content1content2content3)。

每个页面链接到一个JavaScript,该JavaScript使用本地存储来存储用户的输入并在返回时再次显示。

当我更改一个页面上的内容时,它会更改所有三个页面中相同可编辑区域的内容。

我希望每个页面都能够使用相同的脚本来独立于其他页面保存自己的数据。

我已尝试将网页位置(网址)添加到本地存储密钥,以使每个网页使用相同的脚本来存储和检索自己的数据,但我无法获取它工作。我是JavaScript新手 - 非常感谢任何帮助。谢谢!

window.addEventListener('load', onLoad);

function onLoad() {
    checkEdits();
}

// Get page location
var loc = encodeURIComponent(window.location.href);

// Add location to local storage key
function checkEdits() {
    if (localStorage.userEdits1 != null) {
        var userEdits1 = (loc + userEdits1);
        document.getElementById('content1').innerHTML = localStorage.userEdits1;
    }

    if (localStorage.userEdits2 != null) {
        var userEdits2 = (loc + userEdits2);
        document.getElementById('content2').innerHTML = localStorage.userEdits2;
    }

    if (localStorage.userEdits3 != null) {
        var userEdits3 = (loc + userEdits3);
        document.getElementById('content3').innerHTML = localStorage.userEdits3;
    }
};

document.onkeyup = function (e) {
    e = e || window.event;
    console.log(e.keyCode);

    saveEdits();
};

function saveEdits() {
    // Get editable elements
    var editElem1 = document.getElementById('content1');
    var editElem2 = document.getElementById('content2');
    var editElem3 = document.getElementById('content3');

    // Get edited elements contents
    var userVersion1 = editElem1.innerHTML;
    var userVersion2 = editElem2.innerHTML;
    var userVersion3 = editElem3.innerHTML;

    // Add page location to storage key
    var userEdits1 = (loc + userEdits1);
    var userEdits2 = (loc + userEdits2);
    var userEdits3 = (loc + userEdits3);

    // Save the content to local storage
    localStorage.userEdits1 = userVersion1;
    localStorage.userEdits2 = userVersion2;
    localStorage.userEdits3 = userVersion3;
};

function clearLocal() {
    if (confirm('Are you sure you want to clear your notes on this page?')) {
        localStorage.setItem("userEdits1", "");
        localStorage.setItem("userEdits2", "");
        localStorage.setItem("userEdits3", "");

        document.getElementById('content1').innerHTML = "";
        document.getElementById('content2').innerHTML = "";
        document.getElementById('content3').innerHTML = "";

        alert('Notes cleared');
    }
}

2 个答案:

答案 0 :(得分:1)

您的脚本的实际问题是:

localStorage.userEdits1

要使用字符串访问对象的属性(例如存储在变量中),您必须使用括号表示法:

locationStorage[userEdits1]

但我会提出一个稍微更通用的(并且,imho,更清洁)解决方案......

将可编辑元素的内容存储在对象

var cache = {
    <elementX id>: <content>,
    <elementY id>: <content>,
    <elementZ id>: <content>,
    ...
};

然后使用特定于页面的密钥

将此“缓存”存储在本地存储中
localStorage.setItem(window.location.pathName, JSON.stringify(cache));

可能的实施可能是:

window.addEventListener('load', checkEdits);
getContentEditables().forEach(function(editable) {
  // This prevents the function to execute on every keyup event 
  // Instead it will only be executed 100ms after the last keyup
  var debouncedFunc = debounce(100, function(e) {
    saveEdits();
  });

  editable.addEventListener("keyup", debouncedFunc);
});


function checkEdits() {
  var cache = localStorage.getItem(window.location.pathName);

  if (cache !== null) {
    cache = JSON.parse(cache);

    Object.keys(cache)
      .forEach(function(key) {
        var element = document.getElementById(key);

        if (element !== null) {
          element.innerHTML = cache[key];
        }
      });
  }
}

function saveEdits() {
  var cache = {};

  getContentEditables().forEach(function(element) {
    cache[element.id] = element.innerHTML;
  });

  localStorage.setItem(window.location.pathName, JSON.stringify(cache));
};

function clearLocal() {
  if (confirm('Are you sure you want to clear your notes on this page?')) {
    localStorage.removeItem(window.location.pathName);

    getContentEditables().forEach(function(element) {
      element.innerHTML = "";
    });

    alert('Notes cleared');
  }
}


// helper
function getContentEditables() {
  var elements = [];

  document.querySelectorAll("[contenteditable]")
    .forEach(function(element) {
      if (element.id) {
        elements.push(element);
      }
    });

  return elements;
}

function debounce(timeout, func) {
  var timeoutId;

  return function() {
    var that = this,
        args = arguments;

    clearTimeout(timeoutId);

    timeoutId = setTimeout(function() {
      func.apply(that, args);
    }, timeout);
  }
}

答案 1 :(得分:0)

使用

localStorage[userEdits1]

而不是

localStorage.userEdits1