【发布时间】:2022-01-23 04:33:26
【问题描述】:
我在一页上有多个产品表单。每个表单中都有多个颜色选项(单选按钮),带有 available 或 unavailable 属性。
我想为每个产品显示一个自定义的添加到购物车按钮,具体取决于所选颜色选项是否可用,即。 if input[available]:checked show .button-available else show .button-unavailable
预期结果
页面加载时,始终会预先选择第一个颜色选项。根据其可用性,应显示相应的按钮。选择更改时,如果需要,按钮应更改。
HTML 结构
<div class="list-item">
<form action="/cart/add" id="add-to-cart-1">
<div class="radios">
<div class="colors">
<input type="radio" name="color" id="1" class="red" value="1" available>
<input type="radio" name="color" id="2" class="blue" value="2" unavailable>
</div>
</div>
<div class="button-available" style="display:none;">
<input type="submit" value="Add to cart">
</div>
<div class="button-unavailable" style="display:none;">
<button>Out of stock</button>
</div>
</form>
</div>
<div class="list-item">
<form action="/cart/add" id="add-to-cart-2">
<div class="radios">
<div class="colors">
<input type="radio" name="color" id="3" class="red" value="3" unavailable>
<input type="radio" name="color" id="4" class="blue" value="4" available>
</div>
</div>
<div class="button-available" style="display:none;">
<input type="submit" value="Add to cart">
</div>
<div class="button-unavailable" style="display:none;">
<button>Out of stock</button>
</div>
</form>
</div>
我对脚本的悲伤尝试
$(document).ready(function() {
var $list = $('.list-item');
$list.each(function(){
if ( $('input[name=color][unavailable]:checked').val() !== 'true' ) {
$(this).closest('.button-available').show();
}
if ( $('input[name=color][available]:checked').val() !== 'true' ) {
$(this).closest('.button-unavailable').show();
}
$('input[name=color]:checked').on('change', function() {
if ($(this).attr('available') == 'true' ) {
$(this).closest('.button-available').show();
$(this).closest('.button-unavailable').hide();
}
else {
$(this).attr('unavailable') == 'true' ) {
$(this).closest('.button-available').show();
$(this).closest('.button-unavailable').show();
}
});
});
提前感谢您的指导。
【问题讨论】: