var dataLayer =[{
'ecommerce': {
'purchase': {
'actionField': {
'id': 'T12345',
'affiliation': 'Online Store',
'revenue': '35.43',
'tax':'4.90',
'shipping': '5.99',
'coupon': 'SUMMER_SALE'
}
}
}
}];
我正在尝试将产品名称和价格动态添加到产品中。 这是代码:
$('.to-buy').click(function() {
$('.sed').each(function() {
var product_name = $(this).find('h5').text();
var product_price = $(this).parent().siblings(".cost").text();
dataLayer.ecommerce.purchase.products.push({
"name" : product_name ,
"price" :product_price
});
});
});
但我收到错误“未捕获类型错误:无法读取未定义的属性“购买””。 我期望数据层如下:
'ecommerce': {
'purchase': {
'actionField': {
'id': 'T12345',
'affiliation': 'Online Store',
'revenue': '35.43',
'tax':'4.90',
'shipping': '5.99',
'coupon': 'SUMMER_SALE'
},
'products': [{
'name': 'Triblend Android T-Shirt',
'price': '15.25'
},
{
'name': 'Donut Friday Scented T-Shirt',
'price': '33.75',
}]
}
}
接受任何帮助。谢谢。
最佳答案
您的dataLayer
是一个数组,因此尝试访问数组的属性ecommerce
会返回undefined
。并且访问未定义的购买会引发异常。
改用dataLayer[0].ecommerce
,或将您的 dataLayer 更改为如下所示的对象:
var dataLayer ={
'ecommerce': {
'purchase': {
'actionField': {
'id': 'T12345',
'affiliation': 'Online Store',
'revenue': '35.43',
'tax':'4.90',
'shipping': '5.99',
'coupon': 'SUMMER_SALE'
}
}
}
};
此外,您的 dataLayer.ecommerce.purchase.products.push
正在访问购买内的产品
,但我在您的 dataLayer 中没有看到任何产品。
将属性products
添加到您的dataLayer
对象
var dataLayer ={
'ecommerce': {
'purchase': {
'actionField': {
'id': 'T12345',
'affiliation': 'Online Store',
'revenue': '35.43',
'tax':'4.90',
'shipping': '5.99',
'coupon': 'SUMMER_SALE'
},
products:[] // Your are missing this
}
}
};
关于JavaScript 错误 "Cannot read property",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44284891/