Javascript 使用jQuery获取期权价值并应用折扣?
我需要编写一个jQuery/Java函数,该函数将从AJAX更新值中获取数字,对其进行清理以删除$,将价格降低一定百分比(discPerc),然后创建一个警报窗口,通知客户降价 这是我到目前为止所拥有的,我意识到我不是最好的程序员Javascript 使用jQuery获取期权价值并应用折扣?,javascript,jquery,ajax,sanitize,Javascript,Jquery,Ajax,Sanitize,我需要编写一个jQuery/Java函数,该函数将从AJAX更新值中获取数字,对其进行清理以删除$,将价格降低一定百分比(discPerc),然后创建一个警报窗口,通知客户降价 这是我到目前为止所拥有的,我意识到我不是最好的程序员 <head> <script type="text/javascript"> function superSalePrice(discPerc) { var optionPrice = $("#productTotal").val(
<head>
<script type="text/javascript">
function superSalePrice(discPerc) {
var optionPrice = $("#productTotal").val();
var applyDisc = optionPrice * discPerc;
var rPrice = Math.round(applyDisc * 1) / 1;
$("tB").click(function() {
alert("With selected options, final price with discounts is $" + rPrice + "!");
};
)
};
</script>
</head>
//THEN the button
<input type="button" id="tB" value="Test Disc. Calc." onclick="superSalePrice(.85);" />
//THEN the option
<td id="productTotal" class="rowElement3"> $3,450.00</td>
函数superSalePrice(discPerc){
var optionPrice=$(“#productTotal”).val();
var applyDisc=期权价格*discPerc;
var rPrice=数学四舍五入(applyDisc*1)/1;
$(“tB”)。单击(函数(){
提醒(“对于所选选项,带折扣的最终价格为$”+rPrice+“!”);
};
)
};
//然后按下按钮
//然后是选项
$3,450.00
我不知道如何清理该值,因此该部分尚未包括在内
谢谢 我认为您需要做一些更改,请尝试以下内容:
function superSalePrice(discPerc) {
var optionPrice = $("#productTotal").html(); // Changed from .val()
var total = parseFloat(optionPrice.replace(/\$/g, "").replace(/,/g, "")); // Added this
var applyDisc = optionPrice * discPerc;
var rPrice = Math.round(applyDisc * 1) / 1; // Didn't check this
// I'm not sure what the following is for, because you are just binding ANOTHER function every time the button is clicked. Maybe you just want the "alert" line
$("tB").click(function() {
alert("With selected options, final price with discounts is $" + rPrice + "!");
});
}
阅读评论 要清理数字,只需用正则表达式删除所有不是数字或点的内容:
>' $3,450.00 '.replace(/[^0-9.]/g, '');
'3450.00'
下面是我如何构造JavaScript的
function superSalePrice(discount) {
var price = $("#productTotal").text();
price = parseFloat(price.replace(/[^0-9.]/g, ''));
price *= discount;
return Math.round(100 * price) / 100;
)
$('#tB').click(function() {
var total = superSalePrice(0.85);
alert("With selected options, final price with discounts is $" + total + "!");
};
以及HTML:
<input type="button" id="tB" value="Test Disc. Calc." />
<td id="productTotal" class="rowElement3">$3,450.00</td>
$3,450.00
此外,您的HTML是无效的
和
元素不能是同级元素。我不认为input和td元素是同级元素,OP只是把它们放在问题中供我们参考。好的一点:)我只是想知道,parseFloat
的第二个参数用于什么?我最近看到了很多,但是找不到关于两个参数可以做什么的文档。它是基数。您可以将字符串转换为任何基,但我喜欢详细地指定基10
。感谢您花时间回复@我错了。只有parseInt
取基数parseFloat
没有。天哪,你是我的英雄!你的贝宝是什么?我能用钱说谢谢吗?哈哈,绝对不行!不过我很高兴我帮了忙。当然也要看看@Blender solution,因为他们指出了很多你也可以使用的好东西…例如消毒,以及事物的整体组织!非常感谢你!你刚刚救了我剩下的周末!您可能需要查看使用的toFixed
方法,该方法将数字转换为字符串,并且只保留指定的小数点()。因此,请执行所有数字计算,并在最后一刻使用toFixed
转换为小数点后两位的字符串。