我正在尝试计算折扣价格,对于单个商品我可以毫无问题地计算折扣价格。我还有“添加更多”按钮来尽可能添加许多项目。因此,在这里,我开始面临计算这些动态添加的输入字段的折扣价格的问题。
我的单个商品的默认折扣计算脚本是
$('#discount_1').change(function(){
var quantity=$('#qty_1').val();
var percent=$('#discount_1').val();
var price=$('#price_1').val();
var tprice = price * quantity
var discountpercent=percent / 100;
var discountprice=(tprice * discountpercent );
$('#total_1').val(tprice - discountprice);
});
我尝试将其更改为以下内容
$(":input[id^='discount_']").change(function(){
var quantity=$(":input[id^='qty_']").val();
var percent=$(":input[id^='discount_']").val();
var price=$(":input[id^='price_']").val();
var tprice = price * quantity
var discountpercent=percent / 100;
var discountprice=(tprice * discountpercent );
$(":input[id^='total_']").val(tprice - discountprice);
});
计算所有具有以qty_
开头的id
属性的商品集的折扣,这实际上似乎无法正常工作。
这是我的jsFiddle
最佳答案
我已对此进行了修改以删除所有 id
。这将清理掉很多多余的垃圾。这是一个 fiddle :http://jsfiddle.net/B5T6R/1/
解决方案涉及事件委托(delegate)。 $(":input[id^='discount_']").on('change'
的问题是 future 的 tr
不会尚存在,所以没有任何东西可以绑定(bind)!
解决办法是:
$("#InputsWrapper").on('change', '.discount'
它将监听整个 InputsWrapper 表上的所有 future 更改,而不仅仅是折扣元素。
关于javascript - 使用javascript动态输入框折扣计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23744452/