计算和触发onchange,并将结果写入html

Calculations and triggering onchange with writing result to html

本文关键字:结果 html onchange 计算      更新时间:2023-09-26

我需要始终填写#totalcost。有一些javascript计算,结果被写入#总成本。我试着把它放在JSFiddle上,但在加载触发功能时没有成功。对于.number输入字段的每次更改,localTotal都设置为localTotal*数值。我需要两个字。localTotal和#totalcost总是填写

.localTotal与.price*.quantity和#totalcost与所有.localTotals 之和

这是HTML

<div class="row"> <div class="col-xs-5">
<span class="glyphicon glyphicon-remove remove" style="cursor:pointer;"></span> Ventura L15220</div>
<div class="col-xs-3 price">2020.20</div>
<div class="col-xs-4"><input type="number" class="form-control quantity" value="1"></div>
<div class="localTotal"></div></div>
<div class="row"> 
<div class="col-xs-5"><span class="glyphicon glyphicon-remove remove" style="cursor:pointer;"></span> Ventura L15220</div>
<div class="col-xs-3 price">30300.20</div><div class="col-xs-4"><input type="number" class="form-control quantity" value="1"></div>
<div class="localTotal"></div></div>
<div class="col-xs-4 head " id="totalcost"></div>

和javascript

 function changeQuantity(){
        $(".quantity").trigger("change");
        console.log("done")
        $('.quantity').change(calculateTotal);
        function calculateTotal(){
            $quantity=$(this);
            $price=$quantity.closest('.row').find('.price').text();
            $quantityValue=$quantity.val();
            $localTotal=$quantity.closest('.row').find('.localTotal');
            $localTotalValue=$quantityValue*$price;
            $quantity.closest('.row').find('.localTotal').text($localTotalValue);
            console.log($localTotalValue);
            var sumToTotal = 0;
            var totalSum=document.getElementById('totalcost');
            $('.localTotal').each(function(){
                sumToTotal += parseFloat($(this).text());
            });
            totalSum.innerHTML=sumToTotal+' грн';
        }
    }

changeQuantity()是在加载时触发的,但与$(".quantity")无关。trigger("change")#totalcost和.localTotal未填充:c

我觉得事情有点混乱。您在.quantity上绑定了一个更改事件,但在.number上触发了一个变更事件。我也不知道为什么,但为什么要把jQuery选择器和"普通"选择器混在一起?

我不确定你到底想做什么,但以下是它的工作原理:

$(".quantity").on('change', function() {
    /* 
     * Your code
     * replace your 'getElementById('total cost') => $("#totalcost")
     * replace your 'totalSum.innerHTML' => totalSum.text(sumToTotal + ' грн');
     */
});

现在,当.quantity更改时,您的回调将被触发。这可以通过手动触发更改事件来完成:$('.quantity').trigger('change');

我也不知道你说的"总是充满"是什么意思。我认为我们遗漏了一些上下文:)

编辑

我希望你不介意,但我重构了你的代码一点

$(".quantity").on('change', function() {
  var context = $(this).closest('.row');
  // Calculate amount
  var amount = parseFloat(context.find(".price").text()) * parseFloat($(this).text());
  // Set the amount
  context.find('.localTotal').text(amount);
  var total = 0;
  $('.localTotal').each(function(el) {
    total += parseFloat($(this).text());
  });
  $("#totalcost").text(total);
});