javascript .push() inserts the same object every time

前端 未结 2 884
故里飘歌
故里飘歌 2020-11-30 15:52

I dont know what I am doing wrong, but I cant push object to an existing object. I have boxes, and calculator, ... after click on box \".items\"

...
相关标签:
2条回答
  • 2020-11-30 16:21

    It's because there is only one object. You never update "activeItem" to reference a new object. Whenever you want to start on a new item, you need to start with a new object:

    activeItem = {};
    
    0 讨论(0)
  • 2020-11-30 16:32

    Well actually its not inserting last one, its inserting the same item every time. The reason is the code -

    var activeItem = {
        itemId : 0,
        itemName: '',
        itemAmount : 0,
        itemPrice : 0
    }
    

    You see, this line creates and initialises the object activeItem. Nowhere else you have instantiated a new one. And thus every time you are modifying it, it is modifying the same item and inserting the same item. To fix, you should instantiate it inside the functions. Something like -

    <other codes>.....
    
    var itemTemplate = function(){
        this.itemId = 0;
        this.itemName = '';
        this.itemAmount = 0;
        this.itemPrice = 0;
        return this;
    };
    
    activeItem = null;
    
    $(desk).on('click', '.items', function(){
    
        activeItem = new itemTemplate();
    
        activeItem.itemId = 0;
        activeItem.itemAmount = 0;
        activeItem.itemPrice = 0;
        item.removeClass('selected-item');
        $(this).toggleClass('selected-item');
    
        activeItem.itemName = $(this).text();
        activeItem.itemId = $(this)[0].dataset.itemid;
        activeItem.itemPrice = $(this)[0].dataset.itemprice;
    
    });
    
    <other codes>....
    
    0 讨论(0)
提交回复
热议问题