jQuery迭代元素

jQuery iterate through elements

本文关键字:元素 迭代 jQuery      更新时间:2023-09-26

我有以下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);
}