gpt4 book ai didi

javascript - jQuery 遍历元素

转载 作者:搜寻专家 更新时间:2023-10-31 22:21:34 25 4
gpt4 key购买 nike

我有以下 HTML。

<div id="price_list">
<input type="text" value="100" class="input_price" />
<input type="text" value="256" class="input_price" />
<input type="text" value="500" class="input_price" />
<input type="text" value="04.26" class="input_price" />
<input type="text" value="156" class="input_price" />
<input type="text" value="052" class="input_price" />
<input type="text" value="692" class="input_price" />
<input type="text" value="25.36" class="input_price" />
<input type="text" value="10.56" class="input_price" />
</div>

获取具有类 input_price 的元素值的 SUM 的最佳方法是什么?

请注意,我很关心性能。我的实际 HTML 有点复杂(有时我有数千个元素)。我尝试使用 .each() 但有时我的浏览器会卡住。这样问题就可以修改为“遍历元素以获取一些数据的最佳方法是什么?”

我的尝试:

var total = 0;

$(".input_price").each(function(){
total+=parseFloat($(this).val());
});

最佳答案

只是因为您关心性能,所以使用纯 JavaScript 和单个 for 循环:

var list = document.getElementById("price_list"),
inputs = list.getElementsByTagName("input"),
total = 0;

for (var i = 0, len = inputs.length; i < len; i++) {
total += +inputs[i].value;
}

console.log(total);

关于javascript - jQuery 遍历元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16609003/

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