0

我正在尝试使按钮在选择特定选项时发生变化。或者,如果有人能告诉我如何更改一些文本和价格以最小化代码,那就太好了!

    Bundles
<br>
<select id="select-quantity">
    <option value="NONE">None</option>
    <option value="SIX">Quanitiy 6 ($5.00)</option>
    <option value="TWELVE">Quanitiy 12 ($10.00)</option>
    <option value="TWNFOUR">Quanitiy 24 ($20.00)</option>
$('#select-quantity').change(function() {
    var s = $('.snipcart-add-item[data-item-id="' + $(this).val() + '"]');
});
</select>
<br>
<br>
<button class="snipcart-add-item" id="my-button"
 style="border: 0; background: transparent"
 data-item-id="NONE"
 data-item-url="/"
 data-item-name="1 Yin Yang Sticker"
 data-item-price="2.00"
 data-item-quantity="1">
 <img src="http://i.imgur.com/EZ6gneV.png" alt="Add To Cart">
</button>

<button class="snipcart-add-item" style="display: none"
 data-item-id="SIX"
 data-item-url="/"
 data-item-name="6 Yin Yang Stickers"
 data-item-price="5.00">
 <img src="http://i.imgur.com/EZ6gneV.png" alt="Add To Cart">
</button>

<button class="snipcart-add-item" style="display: none"
 data-item-id="TWELVE"
 data-item-url="/"
 data-item-name="12 Yin Yang Stickers"
 data-item-price="10.00">
 <img src="http://i.imgur.com/EZ6gneV.png" alt="Add To Cart">
</button>

<button class="snipcart-add-item" style="display: none"
 data-item-id="TWNFOUR"
 data-item-url="/"
 data-item-name="24 Yin Yang Stickers"
 data-item-price="20.00">
 <img src="http://i.imgur.com/EZ6gneV.png" alt="Add To Cart">
</button>
4

1 回答 1

0

您的代码不可维护,因此我做了一些我认为非常重要的更改,例如:

您不需要处理每个项目的显示/隐藏按钮,这很草率。相反,您应该做的是根据所选值更改按钮的参数。

$(document).ready(function() {
    $('#select-quantity').change(function() {
        var s = $('#my-button');
        var val = $(this).val();
        // Unit Prices Object
        var unitPrices = {1: 2.00, 6: 5.00, 12: 10.00, 24: 20.00};
        // Change the attributes based on the selection
        s.attr('data-item-name', val + ' Ying Yang Sticker');
        s.attr('data-item-price', unitPrices[val]);
        s.attr('data-item-quantity', 1);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<select id="select-quantity">
    <option value="1">None</option>
    <option value="6">Quanitiy 6 ($5.00)</option>
    <option value="12">Quanitiy 12 ($10.00)</option>
    <option value="24">Quanitiy 24 ($20.00)</option>
</select>
<br>
<br>

<button class="snipcart-add-item" id="my-button"
 style="border: 0; background: transparent"
 data-item-id="ADD-ITEM"
 data-item-url="/"
 data-item-name="1 Yin Yang Sticker"
 data-item-price="2.00"
 data-item-quantity="1">
 <img src="http://i.imgur.com/EZ6gneV.png" alt="Add To Cart">
</button>

于 2016-05-30T21:57:40.467 回答