在本地存储中保存JavaScript数据的最佳方法 [英] Best way to save javascript data in localstorage

查看:47
本文介绍了在本地存储中保存JavaScript数据的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够创建JavaScript注释对象并使用导航栏窗格动态删除它们.

I want to be able to create JavaScript note objects and dynamically delete them using a navbar pane.

var sel = window.getSelection();
var range = sel.getRangeAt(0);
var editor = { "startContainer": range.startContainer, "startOffset": range.startOffset, "endContainer": range.endContainer, "endOffset": range.endOffset };

然后使用一条消息,我将位置和消息传递到一个函数中以添加注释:

Then using a message I would pass the location and message into a function to add notes:

Notes(editor, message);
function Notes(location, note) {
  this.location = location;
  this.note = note;
}

我正尽全力围绕如何实际在本地保存数据.

I'm trying to wrap my brain around how to actually save the data locally.

function addNote() {
  // if(tyepof(Storage) !== "undefined"){
  //   if(localStorage.notes){
  //     localStorage.notes
  //   } else {
  //     localStorage.notes = 
  //   }

  localStorage.setItem()
}

localStorage是要走的路吗?我知道sessionStorage只存储一个会话.

Is localStorage the way to go? I know sessionStorage only stores for a session.

推荐答案

这是从 localStorage.getItem()调用中生成一些元素的快速方法,也许还可以帮助您纳尔逊的回答.单击小提琴中的按钮,您将看到代码获取localStorage对象,并使用它们创建一些简单的< li> .

Here's a quick way to generate a few elements from a localStorage.getItem() call and could maybe also help you out here along with Nelson's answer. Click on the button in the fiddle and you'll see the code grab the localStorage objects and use them to create some simple <li>'s.

提琴: http://jsfiddle.net/kfrvdnux/

示例代码:

HTML

<button id='save'>Click the save button...</button>
<div id='content'></div>

JS

var content = document.getElementById('content'),
    save    = document.getElementById('save'),
    output  = '<ul>',
    animals = [{
      name: 'bob',
      type: 'dog'
    }, {
      name: 'fred',
      type: 'lizard'
    }];

// set on load for testing
localStorage.setItem('animals', JSON.stringify(animals));

// grab localStorage data on click and create a list
save.addEventListener('click', function() {
    var ls = JSON.parse(localStorage.getItem('animals'));  
    for (var i = 0; i < ls.length; i++) {
      output += '<li>' + ls[i].name + ', ' + ls[i].type + '</li>';
    }

  output += '</ul>';
  content.innerHTML = output;
});

这篇关于在本地存储中保存JavaScript数据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆