尝试在 Bigcommerce Classic Next 主题中使用 jQuery 在 document.ready 处触发对产品选项的点击

Trying to trigger clicks on product options at document.ready with jQuery in Bigcommerce Classic Next theme

好的,所以我的产品着陆页没有加载特定产品选项的选项,这在将电子商务网站与特定尺寸的产品 Feed 及其各自的价格、重量等相关联时会产生一个大问题。所以我有某个产品的登录页面,我需要根据 URI 参数在 document.ready 上加载特定选项。我想传递 "size" 并根据查询字符串触发对 Twin、Full、Queen 或 King 的点击。这是我正在查看的示例:mattress product page。不过,我离解析和处理参数还差得很远。

我的问题是我一下子跳进了 HTML、CSS、Javascript 和 jQuery,而且我不是 100%正在做这个。现在我只是想确定我应该在哪个 object 上触发点击。我发现的所有教程都有一个名称供参考,如本例 jQuery not triggering on radio button change 所示。我已经在 chrome 的开发者控制台中尝试了以下尝试的一系列组合,但它似乎不包括 header.[=19 中引用的 jQuery 脚本=]

如果有人可以解释我应该使用哪个 class 或选择器 object,它在脚本中的操作方式以及它在 [=47 中的显示方式=],我将不胜感激。另外,如果大家有什么参考书可以推荐一下。

是不是应该像

$(".ProductOptionList option:first").click();

$(".VariationSelect:eq(*index of array of selections I want to click*)").something? attr()? var()? html()? 

以下是 javascript

的(希望)相关部分

来自 product.js:

$(document).ready(function() {

...

// disable all but the first variation box
$(".VariationSelect:gt(0)").attr('disabled', 'disabled');

var prodVarSelectionMap = {}
$(".VariationSelect").change(function() {
    // cache a map of currently selected values.
    var mapIndex = 0;
    $('.VariationSelect').each(function() {
        prodVarSelectionMap[mapIndex] = this.value;
        mapIndex++;
    });

    // get the index of this select
    var index = $('.VariationSelect').index($(this));

    // deselected an option, disable all select's greater than this
    if (this.selectedIndex == 0) {
        $('.VariationSelect:gt(' + index + ')').attr('disabled', 'disabled')
        updateSelectedVariation($('body'));
        return;
    }
    else {
        // disable selects greater than the next
        $('.VariationSelect:gt(' + (index + 1) + ')').attr('disabled', 'disabled')
    }

    //serialize the options of the variation selects
    var optionIds = '';
    $('.VariationSelect:lt(' + (index + 1) + ')').each(function() {
        if (optionIds != '') {
            optionIds += ',';
        }

        optionIds += $(this).val();
    });
    // request values for this option
    $.getJSON(
        '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionIds,
        function(data) {
            // were options returned?
            if (data.hasOptions) {
                // load options into the next select, disable and focus it
                $('.VariationSelect:eq(' + (index + 1) + ') option:gt(0)').remove();
                $('.VariationSelect:eq(' + (index + 1) + ')').append(data.options).attr('disabled', false).focus();

                // auto select previously selected option, and cascade down, if possible
                var preVal = prodVarSelectionMap[(index + 1)];
                if (preVal != '') {
                    var preOption = $('.VariationSelect:eq(' + (index + 1) + ') option[value=' +preVal+']');
                    if (preOption) {
                        preOption.attr('selected', true);
                        $('.VariationSelect:eq(' + (index + 1) + ')').trigger('change');
                    }
                }
            }
            else if (data.comboFound) { // was a combination found instead?
                // display price, image etc
                updateSelectedVariation($('body'), data, data.combinationid);
            }
        }
    );
});

//radio button variations
$('.ProductOptionList input[type=radio]').click(function() {
    //current selected option id
    var optionId = $(this).val();
    // request values for this option
    $.getJSON(
        '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionId,
        function(data) {
            if (!data) {
                return;
            }

            if (data.comboFound) { // was a combination found instead?
                // display price, image etc
                updateSelectedVariation($('body'), data, data.combinationid);
            }
        }
    );
});

来自 product.functions.js:

/* Product Variations */
var baseProduct = {};

function updateSelectedVariation(parent, variation, id) {
    if(typeof(parent) == 'undefined') {
        parent = $('body');
    }
    else {
        parent = $(parent);
    }

    if (typeof id == 'undefined') {
        id = '';
    }

    if(typeof(baseProduct.price) == 'undefined') {
        if($('.AddCartButton', parent).css('display') == "none") {
            var cartVisible = false;
        }
        else {
            var cartVisible = true;
        }

        var stockMessageVisible = false;
        if($('.OutOfStockMessage', parent).css('display') != 'none') {
            stockMessageVisible = true;
        }

        var price;
        $('.VariationProductPrice', parent).each(function(){
            var $$ = $(this);
            if ($$.is('input')) {
                price = $$.val();
            } else {
                price = $$.html();
            }
        });

        baseProduct = {
            saveAmount: $.trim($('.YouSaveAmount', parent).html()),
            price: $.trim(price),
            sku: $.trim($('.VariationProductSKU', parent).html()),
            weight: $.trim($('.VariationProductWeight', parent).html()),
            thumb: $.trim($('.ProductThumbImage img', parent).attr('src')),
            cartButton: cartVisible,
            stockMessage: stockMessageVisible,
            stockMessageText: $('.OutOfStockMessage', parent).html()
        };

    }

// Show the defaults again
    if(typeof(variation) == 'undefined') {
        $('.WishListVariationId', parent).val('');
        $('.CartVariationId', parent).val('');
        if(baseProduct.saveAmount) {
            $('.YouSave', parent).show();
            $('.YouSaveAmount').html(baseProduct.saveAmount);
        } else {
            $('.YouSave', parent).hide();
        } 
        $('.VariationProductPrice', parent).each(function(){
            var $$ = $(this);
            if ($$.is('input')) {
                $$.val(baseProduct.price);
            } else {
                $$.html(baseProduct.price);
            }
        });
        $('.VariationProductSKU', parent).html(baseProduct.sku);
        $('.VariationProductWeight', parent).html(baseProduct.weight);
        $('.ProductThumbImage img', parent).attr('src', baseProduct.thumb);
        $(parent).attr('currentVariation', '');
        $(parent).attr('currentVariationImage', '')
        if(baseProduct.sku == '') {
            $('.ProductSKU', parent).hide();
        }
        if(baseProduct.cartButton) {
            $('.AddCartButton', parent).show();
            if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
                $('.QuantityInput', parent).show();
            }
        }

        if(baseProduct.stockMessage) {
            $('.OutOfStockMessage', parent)
                .show()
                .html(baseProduct.stockMessageText)
            ;
        }
        else {
            $('.OutOfStockMessage').hide();
        }

        $('.InventoryLevel', parent).hide();
    }
// Otherwise, showing a specific variation
    else {
        $('.WishListVariationId', parent).val(id);
        $('.CartVariationId', parent).val(id);

        $('.VariationProductPrice', parent).each(function(){
            var $$ = $(this),
                price = baseProduct.price;
                price = '777';

            if (variation.price !== undefined) {
                price = variation.price;
            }

            if ($$.is('input')) {
                $$.val(price.replace(/[^0-9\.,]/g, ''));
            } else {
                $$.html(price);
            }
        });

        if(variation.sku != '') {
            $('.VariationProductSKU', parent).html(variation.sku);
            $('.ProductSKU', parent).show();
        }
        else {
            $('.VariationProductSKU', parent).html(baseProduct.sku);
            if(baseProduct.sku) {
                $('.ProductSKU', parent).show();
            }
            else {
                $('.ProductSKU', parent).hide();
            }
        }
        $('.VariationProductWeight', parent).html(variation.weight);
        if(variation.instock == true) {
            $('.AddCartButton', parent).show();
            if(typeof ShowAddToCartQtyBox != 'undefined' && ShowAddToCartQtyBox=='1') {
                $('.QuantityInput', parent).show();
            }
            $('.OutOfStockMessage', parent).hide();
        }
        else {
            $('.AddCartButton, .QuantityInput', parent).hide();
            $('.OutOfStockMessage', parent).html(lang.VariationSoldOutMessage);
            $('.OutOfStockMessage', parent).show();
        }
        if(variation.thumb != '') {
            ShowVariationThumb = true;
            $('.ProductThumbImage img', parent).attr('src', variation.thumb);
            $(parent).attr('currentVariation', id);
            $(parent).attr('currentVariationImage', variation.image);

            $('.ProductThumbImage a').attr("href", variation.image);
        }
        else {
            $('.ProductThumbImage img', parent).attr('src', baseProduct.thumb);
            $(parent).attr('currentVariation', '');
            $(parent).attr('currentVariationImage', '')
        }
        if(variation.stock && parseInt(variation.stock)) {
            $('.InventoryLevel', parent).show();
            $('.VariationProductInventory', parent).html(variation.stock);
        }
        else {
            $('.InventoryLevel', parent).hide();
        }
        if(variation.saveAmount) {
            $('.YouSave', parent).show();
            $('.YouSaveAmount').html(variation.saveAmount);
            $('.RetailPrice').show();
        } else {
            $('.YouSave', parent).hide();
            $('.RetailPrice').hide();
        }
    }
}


function GenerateProductTabs()
{
    var ActiveTab = 'Active';
    var ProductTab = '';
    var TabNames = new Array();

    TabNames['ProductDescription'] = lang.Description;
    TabNames['ProductWarranty'] = lang.Warranty;
    TabNames['ProductOtherDetails'] = lang.OtherDetails;
    TabNames['SimilarProductsByTag'] = lang.ProductTags;
    TabNames['ProductByCategory'] = lang.SimilarProducts;
    TabNames['ProductReviews'] = lang.Reviews;
    TabNames['ProductVideos'] = lang.ProductVideos;
    TabNames['SimilarProductsByCustomerViews'] = lang.SimilarProductsByCustomerViews;
    $('.Content .Moveable').each (function() {
        if (this.id == 'ProductBreadcrumb' ||
            this.id == 'ProductDetails' ||
            $(this).html() == '' ||
            !TabNames[this.id]
            ) {
            return;
        }

        TabName = TabNames[this.id];
        ProductTab += '<li id="'+this.id+'_Tab" class="'+ActiveTab+'"><a    onclick="ActiveProductTab(\''+this.id+'_Tab\'); return false;" href="#">'+TabName+'</a></li>';

        if (ActiveTab == '')
        {
        $('#'+this.id).hide();
        }
        $('#'+this.id).removeClass('Moveable');
        ActiveTab = "";
    });

    if (ProductTab != '')
    {
        $('#ProductTabsList').html(ProductTab);
    }
}

这是来自开发控制台:

<div class="productAttributeList" style="">
            <div class="productAttributeRow productAttributeConfigurablePickListSet productAttributeRuleCondition" id="a02034dba575c64f27ad8724b46b9d4d">
    <div class="productAttributeLabel">
        <label for="93a2b37dabd1fe9deae210d2ac0a6b80">
                            <span class="required">*</span>
                        <span class="name">
            Mattress Size:          </span>
        </label>
     </div>
     <div class="productAttributeValue">

 <div class="productOptionViewRectangle">
    <ul class="list-horizontal">
                        <li class="option selectedValue">
        <label for="a224072f64cc4ad05f0cabb0ec516c7d">
            <input type="radio" class="validation" name="attribute[251]" value="2" id="a224072f64cc4ad05f0cabb0ec516c7d">
            <span class="name">TwinXL</span>
        </label>
    </li>

                        <li class="option">
        <label for="b0204680fe57cec48dab9edc28a34a7d">
            <input type="radio" class="validation" name="attribute[251]" value="3" id="b0204680fe57cec48dab9edc28a34a7d">
            <span class="name">Full</span>
        </label>
    </li>

                        <li class="option">
        <label for="83f68b784f33ebf11dbde126b9a9fc97">
            <input type="radio" class="validation" name="attribute[251]" value="4" id="83f68b784f33ebf11dbde126b9a9fc97">
            <span class="name">Queen</span>
        </label>
    </li>

                        <li class="option">
        <label for="fe4651efe956ed8fb3f9b0635e35322d">
            <input type="radio" class="validation" name="attribute[251]" value="5" id="fe4651efe956ed8fb3f9b0635e35322d">
            <span class="name">King</span>
        </label>
    </li>

                        <li class="option">
         <label for="c6c1071e4bc6a5edfd0524dd8ad042c2">
            <input type="radio" class="validation" name="attribute[251]" value="6" id="c6c1071e4bc6a5edfd0524dd8ad042c2">
            <span class="name">California King</span>
        </label>
    </li>

                    </ul>
</div>
    </div>
    <div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet productAttributeRuleCondition" id="668978c662c62cf05439063491e89dc9">
    <div class="productAttributeLabel">
        <label for="e58baa61c3f97085e9c2e7742dbf1595">
                            <span class="required">*</span>
                        <span class="name">
                Add Box Spring Foundation:          </span>
        </label>
    </div>
    <div class="productAttributeValue">
    <div class="productOptionViewSelect">
    <div class="selector fixedWidth" id="uniform-e58baa61c3f97085e9c2e7742dbf1595"><span style="-webkit-user-select: none;">Mattress Only</span><select class="validation" id="e58baa61c3f97085e9c2e7742dbf1595" name="attribute[1123]">
         <option value="">
                            -- Please Choose an Option --                       </option>

                    <option value="36" selected="selected">Mattress Only</option>
                    <option value="37">Standard Height (9")</option>
                    <option value="38">Low Profile (5")</option>
            </select></div>
</div>  </div>
    <div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet" id="11d522cf8329ffc8cb74e3c2934a9a3d">
    <div class="productAttributeLabel">
        <label for="fbde0c153d55c827e931b260145f3442">
                        <span class="name">
                Add Premium Bed Frame:          </span>
        </label>
    </div>
    <div class="productAttributeValue">
    <div class="productOptionViewSelect">
    <div class="selector fixedWidth" id="uniform-fbde0c153d55c827e931b260145f3442"><span style="-webkit-user-select: none;">
                            -- None --
                    </span><select class="validation" id="fbde0c153d55c827e931b260145f3442" name="attribute[1136]">
        <option value="" selected="selected">
                            -- None --
                    </option>

                    <option value="35">Add Bed Frame</option>
            </select></div>
</div>  </div>
    <div class="cf"></div>
</div>
<div class="productAttributeRow productAttributeConfigurablePickListSet" id="d8e2352c51c3bff1643b103c8e92f5bd">
    <div class="productAttributeLabel">
        <label for="96ce2d73c8b6a02a747111a1b793442c">
                        <span class="name">
                Add Premium Mattress Protector:         </span>
        </label>
    </div>
    <div class="productAttributeValue">
    <div class="productOptionViewSelect">
    <div class="selector fixedWidth" id="uniform-96ce2d73c8b6a02a747111a1b793442c"><span style="-webkit-user-select: none;">
                            -- None --
                    </span><select class="validation"  id="96ce2d73c8b6a02a747111a1b793442c" name="attribute[1149]">
        <option value="" selected="selected">
                            -- None --
                    </option>

                    <option value="34">Add Mattress Protector</option>
            </select></div>
</div>  </div

如果您正在使用收音机并尝试去 select 所有然后 select 一个特定的,您需要两件事:名称和唯一标识符。使用名称去select那个组里的所有,用ID去select你需要的那个。如果你没有身份证,你总是可以使用价值。或者,如果您只想 select 第一个可用,请使用名称获取 radio/check 组,并使用 .first() 过滤器获取第一个匹配的元素。

关于 select 的信息:http://api.jquery.com/category/selectors/

如何使用属性 select 或用于名称或值:http://api.jquery.com/attribute-equals-selector/

如何通过ID获取:http://api.jquery.com/id-selector/

触发 "click" 事件也会触发绑定到单击或更改元素的任何事件。如果您需要,请像您尝试的那样触发点击。但是,如果您只需要切换检查状态,则可以使用此方法:How to uncheck a radio button?

作为您评论后的编辑: 很高兴看到您为此使用一些核心 JavaScript。当我使用表单时,我喜欢使用 jQuery 的组合。类似于:

$('[name="attribute[251]"]').each(function() {
    this.checked = false;
});

$('#b0204680fe57cec48dab9edc28a34a7d')[0].checked = true;

每个人对此都有自己的喜好。这只是一个示例方法。

默认Select第一个变体: 将此添加到 Product.html(Bigcommerce 主题文件) 尺码:

$(document).ready(function() {
    $(".productOptionViewRectangle ul").each(function() {
        $(this).children("li").first().addClass("selectedValue");
        $("li.selectedValue input.validation").attr('checked',true);
    });
});

色样:

$(document).ready(function() {
    $(".productOptionPickListSwatch ul").each(function() {
        $(this).children("li").first().addClass("selectedValue");
        $("li.selectedValue input.validation").attr('checked',true);
    });
});