javascript - jQuery 对象通过键获取值

标签 javascript jquery

如何通过键匹配键来获取 assocIMG 的值 eg

如果我有一个 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',
    } 

上面是我正在使用的对象,下面是我当前的 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通过键获取对象成员。您有包含字符串 ("11786") 的变量 prods,以及带有各种键的对象 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);
});

关于javascript - jQuery 对象通过键获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11813800/

相关文章:

javascript - 将值作为数组从 html 传递到 javascript

javascript - 对于循环 jQuery,在 4 项之后重新开始

javascript - 如何使用 jQuery 检测 URL 的变化?

javascript - 什么有助于将输入的数据以 HTML 形式存储在后端页面上?

javascript - Jquery:变量未在回调中初始化?

javascript - 使用 JS 覆盖类的样式,以便更改可以在具有该类的所有元素上可见

javascript - jQuery one() 处理程序执行了两次

javascript - 为什么我的 selenium 停止识别有效的 javascript?

javascript - 链接动态加载的 javascript

javascript - 获取对象内部对象的索引