简体   繁体   English

用累加器遍历jQuery对象?

[英]Iterating over jquery objects with accumulator?

I'm iterating over a collection of objects with $.each and appending a pre-defined attribute of each of them to the page. 我正在使用$ .each遍历对象的集合,并将每个对象的预定义属性附加到页面。 This works just fine. 这样很好。

$(myObjects).each(function(i) {
    var element = $("<tr>").appendTo(tableBody);
    $("<td>").append(this.unitCount).appendTo(element);
});

The value that I am appending is a number. 我要附加的值是一个数字。 I'd like to keep track of these values in an accumulator and return the total to use elsewhere. 我想在累加器中跟踪这些值,然后将总计返回给其他地方使用。 Like this: 像这样:

var total = 0;
$(myObjects).each(function(i) {
    var element = $("<tr>").appendTo(tableBody);
    $("<td>").append(this.unitCount).appendTo(element);
    var total = total + this.unitCount;
});

The problem is that since $(myObjects) is a collection of objects the accumulator variable total isn't recognized inside the loop. 问题在于,由于$(myObjects)是对象的集合,因此在循环内部无法识别累加器变量total。 (When I call console.log(total) right after the loop is started the value inside recognized). (当我在循环开始后立即调用console.log(total)时,将识别内部的值)。 I'd like to use one loop to append the value to the page as well as keep track of the total. 我想使用一个循环将值附加到页面上,并跟踪总数。 Is this possible? 这可能吗?

It's quite slow to create elements inside an each or for loop, instead construct a HTML string representation. 在each或for循环内创建元素,而不是构造HTML字符串表示形式,这相当慢。 Append it once you're done with your data-loop: 完成数据循环后将其追加:

jsBin demo jsBin演示

var TR = "";
var total = 0;

$.each(myObjects, function() {
   var uc = this.unitCount;
   TR += "<tr><td>"+ uc +"</td></tr>";
   total += uc;
});

tableBody.append(TR).append("<tr><td>TOTAL: "+ total +"</td></td>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM