浏览文章

文章信息

Magento2.3 自动选择第一个产品|autoselect configuration product first child product|2.4以上不支持 13342

主题中文件:

Magento_ConfigurableProduct/web/js/configurable.js

找到方法_fillSelect代码修改

 /**
         * Populates an option's selectable choices.
         * @private
         * @param {*} element - Element associated with a configurable option.
         */
        _fillSelect: function (element) {
            var attributeId = element.id.replace(/[a-z]*/, ''),
                options = this._getAttributeOptions(attributeId),
                prevConfig,
                index = 1,
                allowedProducts,
                i,
                j;
            this._clearSelect(element);
            element.options[0] = new Option('', '');
            element.options[0].innerHTML = this.options.spConfig.chooseText;
            prevConfig = false;
            if (element.prevSetting) {
                prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
            }
            if (options) {
                for (i = 0; i < options.length; i++) {
                    allowedProducts = [];
                    /* eslint-disable max-depth */
                    if (prevConfig) {
                        for (j = 0; j < options[i].products.length; j++) {
                            // prevConfig.config can be undefined
                            if (prevConfig.config &&
                                prevConfig.config.allowedProducts &&
                                prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1) {
                                allowedProducts.push(options[i].products[j]);
                            }
                        }
                    } else {
                        allowedProducts = options[i].products.slice(0);
                    }
                    if (allowedProducts.length > 0) {
                        options[i].allowedProducts = allowedProducts;
                        element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);
                        if (typeof options[i].price !== 'undefined') {
                            element.options[index].setAttribute('price', options[i].prices);
                        }
                        element.options[index].config = options[i];
                        index++;
                    }
                    // 自动选择: 添加到选择选项的代码
                    if (i === 0) {
                        this.options.values[attributeId] = options[i].id;
                    }
                    /* eslint-enable max-depth */
                }
                //自动选择:添加的代码用于检查是否在url中设置了配置,并在需要时重置它们
                if (window.location.href.indexOf('#') !== -1) {this._parseQueryParams(window.location.href.substr(window.location.href.indexOf('#') + 1));}
            }
        }

Magento_Swatches/web/js/swatch-renderer.js

找到以方法_RenderControls

/**
         * Render controls
         *
         * @private
         */
        _RenderControls: function () {
            let selectedArray = []; // 自动选择代码: 元素数组的变量declation
            var $widget = this,
                container = this.element,
                classes = this.options.classes,
                chooseText = this.options.jsonConfig.chooseText;
            $widget.optionsMap = {};
            $.each(this.options.jsonConfig.attributes, function () {
                var item = this,
                    controlLabelId = 'option-label-' + item.code + '-' + item.id,
                    options = $widget._RenderSwatchOptions(item, controlLabelId),
                    select = $widget._RenderSwatchSelect(item, chooseText),
                    input = $widget._RenderFormInput(item),
                    listLabel = '',
                    label = '';
                // Show only swatch controls
                if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id)) {
                    return;
                }
                if ($widget.options.enableControlLabel) {
                    label +=
                        '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' +
                        item.label +
                        '</span>' +
                        '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>';
                }
                if ($widget.inProductList) {
                    $widget.productForm.append(input);
                    input = '';
                    listLabel = 'aria-label="' + item.label + '"';
                } else {
                    listLabel = 'aria-labelledby="' + controlLabelId + '"';
                }
                // Create new control
                container.append(
                    '<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
                    'attribute-code="' + item.code + '" ' +
                    'attribute-id="' + item.id + '">' +
                    label +
                    '<div aria-activedescendant="" ' +
                    'tabindex="0" ' +
                    'aria-invalid="false" ' +
                    'aria-required="true" ' +
                    'role="listbox" ' + listLabel +
                    'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
                    options + select +
                    '</div>' + input +
                    '</div>'
                );
                $widget.optionsMap[item.id] = {};
                // Aggregate options array to hash (key => value)
                $.each(item.options, function (i, v) {
                    if (this.products.length > 0) {
                        $widget.optionsMap[item.id][this.id] = {
                            price: parseInt(
                                $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount,
                                10
                            ),
                            products: this.products
                        };
                        // 自动选择代码:生成swatch自动选择的数组
                        if (i === 0) selectedArray.push({id: 'option-label-'+item.code+'-' + item.id + '-item-' + this.id});
                    }
                });
            });
            // Connect Tooltip
            container
                .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]')
                .SwatchRendererTooltip();
            // Hide all elements below more button
            $('.' + classes.moreButton).nextAll().hide();
            // Handle events like click or change
            $widget._EventListener();
            // Rewind options
            $widget._Rewind(container);
            //Emulate click on all swatches from Request
            $widget._EmulateSelected($.parseQuery());
            $widget._EmulateSelected($widget._getSelectedAttributes());
            // 自动选择代码: 异步触发自动选择第一个选项的点击
            console.log('选中的属性...')
            console.log(selectedArray)
            $.each(selectedArray, function (i, v) {
                $('#' + v.id).click();
            });
        }


删除主题对应文件,然后执行

bin/magento s:s:d -f  en_US -t Aiweline/theme

或者:

bin/magento s:s:d -f 

注意:

en_US是语言代码可切换

Aiweline/theme是主题皮肤


完毕!

原创