我有2个价格值,我想计算差异

时间:2014-10-09 13:32:26

标签: javascript jquery

我有2个价格范围。屏幕上显示常规价格和优惠价格,并显示以下HTML。

我正在尝试使用Javascript / jquery计算价格差异,并插入折扣价格的div。

<div class="price-box">
    <p class="old-price">
        <span class="price-label">Regular Price:</span>
        <span class="price" id="old-price-221">Rs17.00 </span>
    </p>
    <p class="special-price">
        <span class="price-label">Special Price</span>
        <span class="price" id="product-price-221">Rs14.45 </span>
    </p>
    <div>
        <span>Discount Price:</span>
        <span>XXXXXX</span>
    </div>
</div>

我还有这个货币符号和价格一起显示。所以,我想知道如何计算“正常价格”和“特价”之间的差异。

有人可以帮助我吗?

P.S。我搜索了网站,没有找到相关的答案。

1 个答案:

答案 0 :(得分:0)

它是:http://jsfiddle.net/s7w98ngt/2/

jQuery部分:

$('.price-box').each(function(){
var element = $(this),
    oldPriceRaw = element.find('.old-price .price').text(),
    specialPriceRaw = element.find('.special-price .price').text(),
    oldPrice = parseFloat(oldPriceRaw.replace('Rs','')),
    specialPrice = parseFloat(specialPriceRaw.replace('Rs','')),
    diff = 'Rs'+(oldPrice - specialPrice).toFixed(2), // 2 numbers after the comma
    diffElement = element.find('.diff-price');
    diffElement.text(diff);


});

HTML有点修改:

<div class="price-box">
<p class="old-price">
<span class="price-label">Regular Price:</span>
<span class="price" id="old-price-221">Rs17.00 </span>
</p>
<p class="special-price">
<span class="price-label">Special Price</span>
<span class="price" id="product-price-221">Rs14.45 </span>
</p>
    <div>
      <span>Discount Price:</span>
      <span class="diff-price"></span>
    </div>
</div>

棘手的是将当前价格值作为浮点数。然后,我们只计算差异。