Javascript 将新对象添加到本地存储

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12162786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:16:37  来源:igfitidea点击:

adding new objects to localstorage

javascripthtmllocal-storage

提问by alexndm

I'm trying to make shopping cart front end with localstorage, as there are some modal windows and I need to pass cart items info there. Every time you click add to cart it should create object and it to localstorage. I know I need to put everything in array and push new object to array, after trying multiple solutions - can't get it to work

我正在尝试使用 localstorage 制作购物车前端,因为有一些模态窗口,我需要在那里传递购物车项目信息。每次单击添加到购物车时,它都应该创建对象并将其添加到本地存储。我知道在尝试多种解决方案后,我需要将所有内容放入数组并将新对象推送到数组 - 无法使其工作

That's what I have (saves only last object):

这就是我所拥有的(仅保存最后一个对象):

var itemContainer = $(el).parents('div.item-container');
var itemObject = {
    'product-name': itemContainer.find('h2.product-name a').text(),
    'product-image': itemContainer.find('div.product-image img').attr('src'),
    'product-price': itemContainer.find('span.product-price').text()
};

localStorage.setItem('itemStored', JSON.stringify(itemObject));

回答by jbabey

You're overwriting the other objects every time, you need to use an array to hold them all:

您每次都覆盖其他对象,您需要使用一个数组来保存它们:

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

var newItem = {
    'product-name': itemContainer.find('h2.product-name a').text(),
    'product-image': itemContainer.find('div.product-image img').attr('src'),
    'product-price': itemContainer.find('span.product-price').text()
};

oldItems.push(newItem);

localStorage.setItem('itemsArray', JSON.stringify(oldItems));

http://jsfiddle.net/JLBaA/1/

http://jsfiddle.net/JLBaA/1/

You may also want to consider using an object instead of an array and use the product name as the key. This will prevent duplicate entries showing up in localStorage.

您可能还需要考虑使用对象而不是数组,并使用产品名称作为键。这将防止在 localStorage 中出现重复的条目。

回答by ChaosPredictor

it's not directly related to local storage but nowdays, it's a good practice to use React/Angular. here is a example:

它与本地存储没有直接关系,但现在,使用 React/Angular 是一个好习惯。这是一个例子:

var TodoItem = React.createClass({
  done: function() {
    this.props.done(this.props.todo);
  },

  render: function() {
    return <li onClick={this.done}>{this.props.todo}</li>
  }
});

var TodoList = React.createClass({
  getInitialState: function() {
    return {
      todos: this.props.todos
    };
  },

  add: function() {
    var todos = this.props.todos;
    todos.push(React.findDOMNode(this.refs.myInput).value);
    React.findDOMNode(this.refs.myInput).value = "";
    localStorage.setItem('todos', JSON.stringify(todos));
    this.setState({ todos: todos });
  },

  done: function(todo) {
    var todos = this.props.todos;
    todos.splice(todos.indexOf(todo), 1);
    localStorage.setItem('todos', JSON.stringify(todos));
    this.setState({ todos: todos });
  },

  render: function() {
    return (
      <div>
        <h1>Todos: {this.props.todos.length}</h1>
        <ul>
        {
          this.state.todos.map(function(todo) {
            return <TodoItem todo={todo} done={this.done} />
          }.bind(this))
        }
        </ul>
        <input type="text" ref="myInput" />
        <button onClick={this.add}>Add</button>
      </div>
    );
  }
});

var todos = JSON.parse(localStorage.getItem('todos')) || [];

React.render(
    <TodoList todos={todos} />,
    document.getElementById('container')
);

from here

这里