javascript – jQuery对象按键获取值

如何通过键匹配键获得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","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',}

上面是我正在使用的对象,下面是我当前的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);

    });

});

解决方法

您可以使用 bracket notation通过其键获取对象成员.你有变量prods包含一个字符串(“11786”),对象assocIMG包含各种键.然后就用吧
assocIMG[prods]

获取与该键相关联的属性值’media / catalog / product / 8795139_633.jpg’.

请注意,您应始终在对象文字中使用字符串作为键,IE不支持那里的数字:

var assocIMG = {
    "11786": 'media/catalog/product/8795139_633.jpg',"11787": 'media/catalog/product/8795139_633.jpg'
};

对脚本的另一个改进是每次都不循环遍历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);
});

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...