问题:Uncaught TypeError: Object #<Object> has no method 'push'
在控制台中。
最佳答案
更改存储项目 id(Cart) 并重试,看起来之前在“购物车”下存储的项目 id 不是 @dc5 在评论部分建议的 json 数组
UPD:试试这个 http://jsfiddle.net/vJkBQ/4/
HTML
<div id='cart'></div>
<input type="button" id="add" value="Add To Cart item 1" />
<input type="button" id="add2" value="Add To Cart item 2" />
Javascript
//TODO: move from globals
var storageName = 'myCART';
$(document).ready(function () {
var item = {
DepartmentID :333,
CategoryID:117,
BrandID:19,
BrandImage:" ",
BrandName:"General",
ID:711
};
var item2 = {
DepartmentID :123,
CategoryID:321,
BrandID:18,
BrandImage:" ",
BrandName:"Common",
ID:712
};
localStorage.clear(storageName);
$('#add').click(function(){
addToCart(item);
});
$('#add2').click(function(){
addToCart(item2);
});
});
function addToCart(item){
//by @slebetman
var items = JSON.parse(localStorage.getItem(storageName));
if (! (items instanceof Array) ) {
items = [];
}
var itemIndex = getItemIndexById(items, item.ID);
if(typeof(itemIndex) === 'number'){
items[itemIndex].quantity++;
}
else{
item.quantity = 1;
items.push(item);
}
localStorage.setItem(storageName, JSON.stringify(items));
console.log(localStorage.getItem(storageName));
}
//find search item index
function getItemIndexById(items, id){
for(var i = 0; i < items.length; i++){
if(items[i].ID == id){
return i;
}
}
return false;
}
关于javascript - Push() 在 JavaScript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18606256/