我有一个关于求和子值的教程,以便使用JavaScript获得基于成本和天数的总值,如下所示。
Facebook Marketing ads
days : 2
Cost : $5
Total : $10
Twitter Marketing ads
days : 10
Cost : $5
Total : $50
Instagram Marketing ads
days : 10
Cost : $10
Total : $100
Total Cost : $50 + $10 + $100= $160
我能够获得所有子价格,但我的问题是将子值相加以获得总价。
这是我的控制台中发生的事情
当我添加第三个项目时,它会生成total cost and also the sub value of the third item selected and takes it as the total cost
当我选择 Facebook营销广告时
the total cost : 10
//这是准确的
当我添加 Twitter营销广告时
the total cost : 60
//这是准确的
当我添加 Instagram营销广告时
the total cost : 160
//准确
the total cost : 100
//但我将此行作为最终值
JS
function select(ad) {
$('.panel').append(
'<div class="marketing">' +
'<p class="name">Ad Selected: ' + ad.name + '</p>' +
'<p class="cost" data-price="' + ad.value + '"> Cost : '+ ad.value+ '</p>' +
'<input type="text" class="days" name="days" /'> +
'<p class="total">Total $:</p>' +
'</div>'
)
$('.panel').on('keyup', '.days', function() {
var marketing = $(this).closest('div');
var days = Number($(this).val());
var cost = Number($(this).closest('div').find('.cost').data('cost'));
marketing.find(".total").text(days * cost);
sum += days * cost;
console.log('the total cost '+sum);
});
}
HTML
<input onclick="return select(this)" type="checkbox" id="{{ad->id}}" name="Facebook" value="{{ad->value}}" />
</div>
<p class="total_ads" style="text-align: center">Total Cost $:</p>
<div class="panel" id="panel"></div>
我是JavaScript和jQuery的初学者。我无法让它在片段中工作