adding new objects to localstorage

前端 未结 2 1151
情歌与酒
情歌与酒 2020-12-05 14:34

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

相关标签:
2条回答
  • 2020-12-05 15:10

    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.

    0 讨论(0)
  • 2020-12-05 15:31

    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

    0 讨论(0)
提交回复
热议问题