gpt4 book ai didi

javascript - 根据属性 JavaScript 计算总和

转载 作者:行者123 更新时间:2023-11-28 00:13:11 25 4
gpt4 key购买 nike

如何计算放入 li 表中的许多不同获取属性的总和?我想每次在 li 表中添加/删除时更新总数......这是代码:JavaScript:

var ele = info[plus.indexOf(this)];

var ul = document.getElementById("cart_id");

var li = document.createElement("LI");

var title = ele.getAttribute("data-title");

var price = parseInt(ele.getAttribute("data-price"));

li.appendChild(document.createTextNode(title+" "+price));
ul.appendChild(li);//So far so good!!


/*Update! when I try this code below, I get current value from (data-price) X 3?
So when I press 299 I get value 897? Why does it count like this?
I want to sum the total!? I guess I have to put [i] inside there
but I don't know which way, I doesn't work if I try:
total += parseInt(listItem[i].ele.getAttribute("data-price")); */

var total = 0;

listItem = ele.getAttribute("data-price");

for (var i=0; i < listItem.length; i++)
{
total += parseInt(ele.getAttribute("data-price"));
}

document.querySelector("#totalPrice").value = total;

HTML:

<div class="cart">
<div id="cart">Cart</div>
<ul class="cart_ul" id="cart_id">
</ul>

<form>
<br>Total price:
<input type="text" name="totalPrice" id="totalPrice" disabled>
</form>
</div>

<ul class="product" id="prod">
<li class="first" data-title="iPad" data-price="299">iPad euro;299)/li>
</ul>

所以我想从“产品 UL-class”获取价格(在本例中为 data-price="299")并将其放入“购物车 UL-class”中。

最佳答案

您可以将新价格添加到现有总价中,也可以重新计算总价。例如:

function getSum() {
var totalPrice = 0;
$('li').each(function () {
totalPrice += parseInt($(this).data('price'));
});
return totalPrice;
}

没有jquery:

var list= document.getElementById("ul");
var listItem = list.getElementsByTagName("li");

var totalPrice = 0;

for (var i=0; i < listItem.length; i++) {
totalPrice += parseInt(listItem[i].getAttribute('data-price'));
}

关于javascript - 根据属性 JavaScript 计算总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30692683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com