我店里有一张商品清单。每种产品都有一个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 );发布于 2015-11-30 22:25:56
您需要使用.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>发布于 2015-11-30 22:26:38
我相信您正在寻找.each函数:http://api.jquery.com/each/
发布于 2015-11-30 22:32:52
https://stackoverflow.com/questions/34009101
复制相似问题