0

我正在尝试使用数组创建一些动态下拉列表,但我无法理解这个概念。当页面加载时,我成功创建了 4 个数组(注意:不是下面的代码,只是数组的表示):

optionsOne ["sm","md","md","sm"]
optionsTwo ["white","white","red","red"]
availOne ["false","true","true","true"]
availTwo ["false","true","true","true"]

两个可用的阵列是相同的,我可以将其缩减为一个阵列,“可用” 这个数据对我来说代表的是您自上而下跟踪产品可用性,因此“sm white”是错误的(不可用)。“md white”是真的。“md red”是真的。“sm red”是真的。

现在我需要创建选择下拉列表,但我不想重复。我目前正在创建两个下拉列表,一个代表大小,一个代表颜色。不幸的是,我的第一个下拉列表显示 4 个项目(sm,md,md,sm),而它只需要显示两个唯一的项目(sm,md)。我的第二个下拉列表显示 4 个项目,但它应该只显示两个并根据第一个的选择进行更新。它应该始终显示“白色,红色”,但在第一个下拉菜单中选择“sm”的情况下,它会将“白色”设置<option>为禁用,因为 sm/white 可用性为假。

我完全不知道如何创建某种数组以使我没有重复项,但仍会在第二个下拉列表中生成正确的结果

optionsOne = [];
optionsTwo = [];
availOne = [];
availTwo = [];

Shopify.updateOptionsInSelector = function(selectorIndex) {
switch (selectorIndex) {
case 0:
var selector = jQuery('.single-option-selector:eq(0)');
break;
case 1:
var selector = jQuery('.single-option-selector:eq(1)');
break;
}
if(selectorIndex===0){
    selector.empty();
    //this is looping and creating duplicates
    for (var i=0; i<optionsOne.length; i++) {
        var option = optionsOne[i];
        var newOption = jQuery('<option></option>').val(option).html(option);
        selector.append(newOption);
    }
}else if(selectorIndex===1){
    selector.empty();
    //this is looping and creating duplicates
    //also, this one should create an option as disabled if the variant is unavailable
    for (var i=0; i<optionsTwo.length; i++) {
        var option = optionsTwo[i];
        var available = availTwo[i];
        //alert('changed the first selector, this item is labeled '+option+' and availability is '+available);
        if(available=="true"){
            var newOption = jQuery('<option></option>').val(option).html(option);
        }else{
            var newOption = jQuery('<option disabled></option>').val(option).html(option);
        }
        selector.append(newOption);
    }
}

selector.trigger('change');
};

Shopify.linkOptionSelectors = function(product) {
// Building our mapping object.
for (var i=0; i<product.variants.length; i++) {
var variant = product.variants[i];
//if (variant.available) {

// Gathering values for the 1st drop-down.
optionsOne.push(variant.option1);
if (variant.available) {
    availOne.push('true');
}else{
    availOne.push('false');
}   

// Gathering values for the 2nd drop-down.
optionsTwo.push(variant.option2);
if (variant.available) {
    availTwo.push('true');
}else{
    availTwo.push('false');
}

optionsOne = Shopify.uniq(optionsOne);
optionsTwo = Shopify.uniq(optionsTwo);

}

// Update options right away.
Shopify.updateOptionsInSelector(0);
if (product.options.length > 1) Shopify.updateOptionsInSelector(1);
// When there is an update in the first dropdown.
jQuery(".single-option-selector:eq(0)").change(function() {
Shopify.updateOptionsInSelector(1);
return true;
});

};
4

0 回答 0