你如何得到assocIMG钥匙匹配钥匙的价值,例如
如果我有一个var 11786我希望它返回media/catalog/product/8795139_633.jpg
var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}
}
};
var assocIMG = // Added - Removed { here, causes issues with other scripts when not working with a configurable product.
{
11786: 'media/catalog/product/8795139_633.jpg',
11787: 'media/catalog/product/8795139_633.jpg',
}
Run Code Online (Sandbox Code Playgroud)
上面是我正在使用的对象,下面是我当前的jQuery.非常感谢帮助.
$('#attribute125').change(function() {
var image = $(this).val();
$.each(spConfig.attributes, function() {
prods = $(this.options).filter( function() { return this.id == image; } )[0].products[0];
alert(prods);
});
});
Run Code Online (Sandbox Code Playgroud)
您可以使用括号表示法通过其键获取对象成员.您有prods包含string("11786")的变量,以及assocIMG包含各种键的对象.然后就用吧
assocIMG[prods]
Run Code Online (Sandbox Code Playgroud)
获取'media/catalog/product/8795139_633.jpg'与该键关联的属性值.
请注意,您应始终在对象文字中使用字符串作为键,IE不支持那里的数字:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg'
};
Run Code Online (Sandbox Code Playgroud)
对脚本的另一个改进是不会spConfig.attributes每次循环,如果图像包含在多个属性中,可能会多次执行您的操作.相反,从中构建一个哈希对象,您可以在其中查找相应的产品ID.
var productById = {};
$.each(spConfig.attributes, function() {
$.each(this.options, function() {
var id = this.id;
productsById[i] = this.products[0];
});
});
$('#attribute').change(function() {
var id = this.value;
var prod = productById[id];
var image = assocIMG[prod];
$("#product_img").attr("src", image);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40665 次 |
| 最近记录: |