我正在寻找有关JavaScript的帮助。我们正在尝试计算并显示折扣前的价格与折扣后的价格之间的百分比差异。相关的类是.from_price和.for_price。价格是160,00和130,00。
所以我们尝试使用这段代码,但它不起作用:
var price = (Math.round($(".from_price").html())).toString();
var sale = (Math.round($(".for_price").html())).toString();
var korting = (Math.round(((sale - price)/price)*100)).toString();
$("#discount").html("You receive" + korting + "%" + " " + "discount");
}
非常感谢你的帮助!
这是因为您使用字符串值来获取折扣值。您可以使用parseFloat()将160,00转换为160
null
function getDiscount() {
var price = parseFloat($(".from_price").html());
var sale = parseFloat($(".for_price").html());
console.log(price);
console.log(sale);
var korting = (Math.round(((sale - price)/price)*100));
$("#discount").html("You receive" + korting + "%" + " " + "discount");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="from_price">160,00</div>
<div class="for_price">130,00</div>
<button type="button" onclick="getDiscount()">get discount</button>
<div id="discount"></div>
这里有一个例子:
null
var price = +((Math.round($(".from_price").html())).toString());
var sale = +((Math.round($(".for_price").html())).toString());
var korting = (Math.round(((sale - price)/price)*100)).toString();
$("#discount").html("You receive "+ korting + " %discount");
console.log(typeof sale);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="from_price">100</div>
<div class="for_price">50</div>
<div id="discount"></div>