所以我试图让我的变量总计在点击时更新。我想显示总金额。
我想要23.9 不是 10.9523.9
https://jsfiddle.net/jdg2384/qtp2zLma/1/
$( document ).ready(function() {
var total = 0;
var arr =[0];
$( ".card" ).on( "click", function() {
console.log(arr);
event.preventDefault();
var food = $(this).find('h4').text();
var price = $(this).find('p').text();
$( "#log" ).prepend(
`<li class="left"><h4>` + food + `</h4></li>`+
`<li class="right"><h5 class="right">`+ price +`</h5></li></br>`
);
$('h5:first').each(function() {
total += Number($(this).text());
});
$( "#totalCost" ).append(total);
});
});
最佳答案
您所做的就是附加到#totalCost
,您只需替换html即可。另外,在您的 jsfiddle 中,您也没有从 p 标记中获取数字。
你的 JavaScript 应该是这样的;
$(document).ready(function() {
var total = 0;
var arr = [0];
$(".card").on("click", function() {
console.log(arr);
event.preventDefault();
var food = $(this).find('h4').text();
var price = $(this).find('p').text();
$("#log").prepend(
`<li class="left"><h4>` + food + `</h4></li>` +
`<li class="right"><h5 class="right">` + price + `</h5></li></br>`
);
$('h5:first').each(function() {
total += Number($(this).text());
});
$('p').each(function() {
total += Number($(this).text());
});
$("#totalCost").html(total);
});
});
祝你好运
关于javascript - 动态变化的总量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46880495/