I have a list of products in my store. Each product has a price in a div. I need to find the price of each product, and calculate a sales price of 30%, and append it to the price in red.
I can do the DOM manipulation for this, but I cant figure out how to loop over the products. This code below appends the sales price of ONLY the first product to all of the products in the list.
Working Fiddle: https://jsfiddle.net/m5fxnLqp/1/
Sample 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>
Here is the DOM Manipulation:
//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 );
you need to use .each() to loop through ".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 );
});
Note: This code will append the new price after discount by using
var priceDiscount = priceNum - priceNum * .30;
if you need just a discount return it back to your code
var priceDiscount = priceNum * .30;
and I think you need to use
$(this).closest('product').append( formattedPrice );
instead of
$(this).append( formattedPrice );
the deference between $(this).append( formattedPrice );
and $(this).closest('product').append( formattedPrice );
$(this).append( formattedPrice );
html after append
<div class="ProductPrice">
$9.99
<div style="color:red;"> $6.99</div>
</div>
$(this).closest('product').append( formattedPrice );
html after append
<li class="product">
<div class="ProductPrice">$9.99</div>
<div style="color:red;"> $6.99</div>
</li>
我相信您正在寻找.each函数: http ://api.jquery.com/each/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.