我目前正在使用一些 javscript,其背后的基本思考过程是,您单击一个链接,然后链接生成并进入篮子,我目前在控制台中记录了发送到篮子的内容。当我单击链接时,它会触发该additem()
功能,
function additem(desc,price,quantity)
{
var x = items.length - 1;
var found = (x == 0);
var y = new Item(desc,price,parseInt(quantity));
console.log(y);
var z = y;
while((x != 0) && (found == false))
{
z = items[x];
if(z != null)
{
if(z.M_desc == desc)
{
found = true;
}
else
{
x--;
}
}
else
{
x--;
}
}
if(found == false)
{
items[++numitems] = y;
}
else
{
items[x].M_quantity += quantity;
}
updatecart();
}
我在控制台中看到的是以下内容,
Item { M_desc="Item 2", M_price="10", M_quantity=1}
但是,当我单击它时,我得到以下信息,
M_desc
"Item 2"
M_price
"10"
M_quantity
undefined
M_quantity 怎么可能是 1,然后在另一个控制台视图中未定义?
===== 编辑 =====
我认为问题源于这里,我的 JS 代码以该行开头。
var items = new Array(2);
现在我假设这会创建一个新数组,因为当我console.log(items)
直接运行它时,我得到[undefined, undefined]
.
additem 使用以下代码在单击链接时调用,
HTML
<a class='product' rel='"+category[i].product[j].price+"' href=''>"+ category[i].product[j].description + "</a>
JS
$('.product').live("click",function(e){
additem($(this).text(), $(this).attr('rel'), 1);
e.preventDefault();
});
这是出现问题的时候,因为items[x]
它总是为空或未定义。我不知道为什么。