我正在努力使其在选择特定选项时按钮发生变化。或者,如果有人可以告诉我如何更改一些文本和价格,以最大限度地减少可能很棒的代码!
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>
答案 0 :(得分: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);
});
});
&#13;
<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>
&#13;