jQuery迭代元素
jQuery iterate through elements
我有以下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
类元素值的和的最佳方法是什么?
请注意我很关心演出。我的实际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);
在jQuery中,您可以直接这样做:
var sum = 0;
$('.input_price').each(function(){
var value = parseFloat(this.value);
if(!isNaN(value)) sum += value;
});
还可以使用计时器进行异步循环。这将需要更长的时间,但不会冻结UI线程,所以你不会卡住。下面是一个演示,它将一个数组的1求和到1000,但不会冻结浏览器。
function loop(object,callback){
var i = 0;
var sum = 0;
var timer = setInterval(function(){
//get value and add
var value = parseFloat(object[i].value);
if(!isNaN(value)) sum += value;
//if we reach the length, clear the timer and call the callback
if(++i === object.length){
clearInterval(timer);
callback(sum);
}
},0);
}
loop($('.input_price'),function(sum){
console.log(sum);
});
var sum = 0;
$('.input_price').each(function(){
sum += parseFloat(this.value);
});
$('.input_price').each(function(){
sum += parseFloat($(this).val());
});
对所有类为input_price的元素求和,
var elements = document.getElementsByClassName("input_price");
var sum = 0;
for(var i=0; i<elements.length; i++) {
sum += parseFloat(elements[i].value);
}
相关文章:
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 为什么这只是迭代 HTMLCollection 的奇怪元素
- 每个$.,循环获胜't逐个迭代HTML元素
- 在JSON数组中进行迭代,并为其元素设置样式
- 使用.ech()迭代具有类似类名的元素
- 自动完成搜索无法正常工作,请不要迭代$中的所有元素.每个ul-li都会及时显示响应
- 迭代 coffeescript 中的 jQuery DOM 元素: $(@).捷径
- 如何迭代具有相同ID的元素
- DOM:如何根据迭代器值设置元素宽度并在mouseover上调用函数
- 在JS对象元素上迭代并更改它们
- 迭代JSON对象并将元素打印到屏幕上的最佳方式是什么
- 如何访问迭代模板中的任何元素
- javascript通过逻辑连接的元素对进行迭代
- 使用for.of迭代时删除集合中的元素是否安全
- 如何在数据数组的每次迭代中创建一个内容为“i+1”的新 HTML 元素
- JQuery 添加表单元素迭代 ID
- 每个,从开始元素迭代
- 无法使用守夜人中的元素迭代元素
- Javascript中的表单元素迭代
- jQuery 从子元素迭代内部子元素