我的商店里有产品清单。每个产品都有一个div的价格。我需要找到每种产品的价格,并计算30%的销售价格,并将其附加到红色的价格。
我可以为此做DOM操作,但我无法弄清楚如何循环产品。以下代码仅将第一个产品的销售价格附加到列表中的所有产品中。
工作小提琴: https://jsfiddle.net/m5fxnLqp/1/
示例HTML:
<ul class="ProductList">
<li class="product">
<div class="ProductPrice">$9.99</div>
</li>
<li class="product">
<div class="ProductPrice">$10.99</div>
</li>
</ul>
这是DOM操作:
//find the price and convert to decimal to work with
var price = $(".ProductPrice").text();
var priceFormat = price.replace("$", "");
var priceNum = parseFloat(priceFormat).toFixed(2);
//calculate the price discount
var priceDiscount = priceNum * .30;
var priceFinal = priceDiscount.toFixed(2);
// Append the formatted price to the div
var formattedPrice = '<div style="color:red;"> $' + priceFinal + '</div>';
$(".ProductPrice").append( formattedPrice );
答案 0 :(得分:2)
您需要使用 .each()来循环浏览".ProductPrice"
//find the price and convert to decimal to work with
$(".ProductPrice").each(function(){
var price = $(this).text();
var priceFormat = price.replace("$", "");
var priceNum = parseFloat(priceFormat).toFixed(2);
//calculate the price discount
var priceDiscount = priceNum - priceNum * .30;
var priceFinal = priceDiscount.toFixed(2);
// Append the formatted price to the div
var formattedPrice = '<div style="color:red;"> $' + priceFinal + '</div>';
$(this).append( formattedPrice );
});
注意:此代码将使用
在折扣后附加新价格var priceDiscount = priceNum - priceNum * .30;
如果您只需要折扣,请将其返回给您的代码
var priceDiscount = priceNum * .30;
我想你需要使用
$(this).closest('product').append( formattedPrice );
而不是
$(this).append( formattedPrice );
$(this).append( formattedPrice );
和$(this).closest('product').append( formattedPrice );
$(this).append( formattedPrice );
html
<div class="ProductPrice">
$9.99
<div style="color:red;"> $6.99</div>
</div>
追加后 $(this).closest('product').append( formattedPrice );
html
<li class="product">
<div class="ProductPrice">$9.99</div>
<div style="color:red;"> $6.99</div>
</li>
答案 1 :(得分:0)
我相信您正在寻找.each函数:http://api.jquery.com/each/
答案 2 :(得分:0)