adding new objects to localstorage

2020-02-08 14:18发布

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

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));

2条回答
beautiful°
2楼-- · 2020-02-08 14:52

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/

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.

查看更多
再贱就再见
3楼-- · 2020-02-08 15:14

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

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

查看更多
登录 后发表回答