我需要计算var packprice
+ var packprices
+ var ala
,这正在for循环中。我正在控制台中获得所有值,但是在tprice
中却没有得到。请帮忙。
$( "#get_total" ).click(function() {
alert('calculation pending');
var idSelector = function() { return this.value; };
var packprices = 0;
var packprice = 0;
var c = $(":checkbox:checked").map(idSelector).get();
for (var i = 0; i < c.length; i++) {
// console.log(c[i]);
// console.log(parseInt($(".longduration_price" + c[i]).val()));
if($(".duration_status" + c[i]).is(':checked'))
{
var packprice = !isNaN(parseInt($(".longduration_price" + c[i]).val())) ? parseInt($(".longduration_price" + c[i]).val()) : 0 ;
console.log(packprice);
}else{
var packprices = !isNaN(parseInt($(".packpriceone" + c[i]).val())) ? parseInt($(".packpriceone" + c[i]).val()) : 0 ;
console.log(packprices);
}
var ala = parseInt($("#alacartprice").val());
var tprice = packprice + packprices + ala;
}
console.log(tprice);
$("#totalprice").val(tprice);
});
答案 0 :(得分:1)
您需要在循环外声明tprice
,然后将结果添加到tprice
,如下所示。
$( "#get_total" ).click(function() {
alert('calculation pending');
var idSelector = function() { return this.value; };
var packprices = 0;
var packprice = 0;
var c = $(":checkbox:checked").map(idSelector).get();
var tprice = 0;
for (var i = 0; i < c.length; i++) {
// console.log(c[i]);
// console.log(parseInt($(".longduration_price" + c[i]).val()));
if($(".duration_status" + c[i]).is(':checked'))
{
var packprice = !isNaN(parseInt($(".longduration_price" + c[i]).val())) ? parseInt($(".longduration_price" + c[i]).val()) : 0 ;
console.log(packprice);
}else{
var packprices = !isNaN(parseInt($(".packpriceone" + c[i]).val())) ? parseInt($(".packpriceone" + c[i]).val()) : 0 ;
console.log(packprices);
}
var ala = parseInt($("#alacartprice").val());
tprice += packprice + packprices + ala;
}
console.log(tprice);
$("#totalprice").val(tprice);
});
答案 1 :(得分:0)
您必须在for循环之前定义变量
$( "#get_total" ).click(function() {
alert('calculation pending');
var idSelector = function() {
return this.value;
};
var packprices = 0;
var packprice = 0;
var c = $(":checkbox:checked").map(idSelector).get();
var tprice = 0
for (var i = 0; i < c.length; i++) {
// console.log(c[i]);
// console.log(parseInt($(".longduration_price" + c[i]).val()));
if ($(".duration_status" + c[i]).is(':checked')) {
var packprice = !isNaN(parseInt($(".longduration_price" + c[i]).val())) ? parseInt($(".longduration_price" + c[i]).val()) : 0;
console.log(packprice);
} else {
var packprices = !isNaN(parseInt($(".packpriceone" + c[i]).val())) ? parseInt($(".packpriceone" + c[i]).val()) : 0;
console.log(packprices);
}
var ala = parseInt($("#alacartprice").val());
tprice = packprice + packprices + ala;
}
console.log(tprice);
$("#totalprice").val(tprice);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 2 :(得分:0)
我们假设您具有如下span元素:
<span id="totalprice"></span>
现在,通过以下代码,您可以设置声明为循环外的值
var currentValue = parseInt($("#totalprice").text(),tprice);