尝试在考虑所选Javascript数量的情况下计算项目的总价

Trying to calculate the total price of items taking into account the quantity selected Javascript

本文关键字:情况下 计算 项目 Javascript      更新时间:2023-09-26

这是我第一次在这个网站上发帖。我有一个网页,概述了我的一个产品,我打算出售

这就是我的困境。我有一个代码,要求用户按下+和-按钮来获得他们想要的物品数量。现在我想弄清楚的是,如果用户按+或-任意次数,我需要能够考虑点击次数,并在单独的一行上计算订单的总价。我是javascript的新手,感谢提供的所有帮助

 <form>
   <br> Item Price: $463.50
   <br> Please Select Quantity
   <input type='button' name='subtract' onclick='javascript:   document.getElementById("qty").value--;' value='-'/>
   <input type='button' name='add' onclick='javascript: document.getElementById("qty").value++;' value='+'/>
   <input type='text' name='qty' id='qty' />
   </form>
<form>
<br> Item Price: $<span id='price'>463.50</span>

    var unitprice = (document.getElementById('price').innerText || document.getElementById('price').textContent);
    var price = parseFloat(unitprice);
    var count = parseInt(document.getElementById("qty").value, 10)
    var total = price * count;
    alert(total); // or do whatever you want

我会将Javascript代码分离成自己的<脚本>元素,并做一些类似的事情:

<form>
   <br/> Item Price: $<span id="price">463.50</span>
   <br/> Please Select Quantity
   <input type="button" name="subtract" id="subtract" value="-"></input>
   <input type="button" name="add" id="add" value="+"></input>
   <input type="text" name="qty" id="qty" value="0"></input>
   <br/> Total 
   <input type="text" name="total" id="total" value="0"></input>
</form>

Javascript看起来像:

$(function() {
   var price = parseFloat($('#price').text());
   $('#subtract').on("click",function() {
       var $qty = $('#qty');
       var current = parseInt($qty.val());
       if ( current > 0 ) {
           $qty.val(current-1);
           $('#total').val(price*(current-1));
       } else {
           $('#total').val(0);
       }
   });
   $('#add').on("click",function() {
       var $qty = $('#qty');
       var current = parseInt($qty.val());
       $qty.val(current+1);
       $('#total').val(price*(current+1));
   });
});

你可以在行动中看到它。

没有jQuery,这一切都是可以做到的,但它让生活变得轻松多了!

既然你提到你是新手,请注意:在真正的应用程序中,只使用页面中的数量,并重新计算在后端收取的费用。对某人来说,在DOM中修改价格或总额是非常容易的;如果你使用DOM的价格或总额,那么恶意用户可以以他们想要的任何价格购买它!始终假设输入是恶意的或不正确的。

var value = parseInt(document.getElementById("qty").value, 10)
item_price = item_price * value;
document.getElementById("someid").innertHTML = item_price;