如果我只列出了一个产品,则此脚本有效。总计是从另一个div父级添加的。什么是最好的做法,以保持脚本只为个别div?
我在一个页面中有50个产品,我在这个片段中只显示了两个。下面是脚本的片段:
https://jsfiddle.net/jboiler/vopa8qt7/30/
<div>
<div class="single-product-items">
<div>
<h5>
<a>Product 1
</a>
</h5>
<span class="current-price">350</span>
</div>
<div class="varSelectorBtns">
<div class="shirtColor"><button value="0" class="White"></button><button value="80" class="Black"></button><button value="80" class="Gray"></button><button class="DarkGray" value="10"></button><button value="80" class="NavyBlue"></button><button value="80" class="Red"></button><button value="80" class="Yellow"></button><button value="80" class="Green"></button><button value="80" class="Blue"></button><button class="Pink" value="30"></button></div>
<div class="shirtSize "><button value="0">XS</button><button value="0">S</button><button value="0">M</button><button value="0">L</button><button value="0">XL</button><button value="20">XXL</button><button value="30">3XL</button><button value="50">5XL</button></div>
<div class="shirtQlty "><button value="0">Ordinary</button><button value="68">Premium</button></div>
<div>
<button>Add To Cart</button>
</div>
</div>
</div>
</div>
产品2、产品3等的代码相同。...
下面是脚本
let subtotalprice = 0;
let sizePrice = 0;
let qualityPrice = 0;
let colorPrice = 0;
let baseprice = 350;
// SIZE BUTTONS
$(".shirtSize button").click(function() {
sizeVal = $(this).text();
sizePrice = $(this).val();
subtotalprice = parseInt(baseprice) + parseInt(sizePrice) + parseInt(qualityPrice) + parseInt(colorPrice);
$(this).closest('.single-product-items').find('.current-price').text( subtotalprice); //change displayed current price
});
// COLOR BUTTONS
$(".shirtColor button").click(function() {
colorVal = $(this).text();
colorPrice = $(this).val();
subtotalprice = parseInt(baseprice) + parseInt(sizePrice) + parseInt(qualityPrice) + parseInt(colorPrice);
$(this).closest('.single-product-items').find('.current-price').text(subtotalprice); //change displayed current price
});
// QUALITY BUTTONS
$(".shirtQlty button").click(function() {
qualityVal = $(this).text();
qualityPrice = $(this).val();
subtotalprice = parseInt(baseprice) + parseInt(sizePrice) + parseInt(qualityPrice) + parseInt(colorPrice);
$(this).closest('.single-product-items').find('.current-price').text(subtotalprice); //change displayed current price
});
1条答案
按热度按时间vaqhlq811#
要使JavaScript代码特定于单个div元素,可以使用
getElementById
或querySelector
方法通过div的id或class来定位div。JavaScript:
或者
使用JavaScript模块如果您有大量特定于div的JavaScript代码,您可以将其封装在JavaScript模块中。这将使代码与代码的其他部分保持分离,并使其更易于维护。