计算 .each 中的术语实例



我有这段代码,它将一个表中的值与另一个表进行比较,并添加一个类(如果存在(,并且该部分有效。 我现在要做的是显示该值存在多少次。 我尝试了增量计数++,但数字已关闭。

function reporgs() {
jQuery('#attendee01 tr:visible').each(function() {
var count=0;
var row = jQuery(this);
var left_cols = jQuery(this).find("td:nth-child(3)");
jQuery('#org01 tr').each(function() {
var right_cols = jQuery(this).find("td:nth-child(1)");
if (left_cols.html() == right_cols.html()) {
count++;
right_cols.css('color', 'red');
right_cols.append(" <b>" + count + "</b>");
}
});
});
}

查看小提琴 https://jsfiddle.net/zjsLqxwp/1/

谢谢大家

更简单的方法怎么样?也许只是使用选择器来匹配元素,让Javascript为您计算出现次数。

jQuery(document).ready(function() {
jQuery("#org01 td").each(function() {
var length = jQuery("#attendee01 td:contains(" + jQuery(this).html() + ")").length;
if (length > 0) {
jQuery(this).css("color","red");
jQuery(this).append(" " + length);
}
});
});

循环嵌套不正确。您的方法应该是遍历组织,并为每个组织统计有多少与会者:

jQuery(document).ready(function() {
reporgs();
//find represented sponsors
function reporgs() {
jQuery('#org01 tr').each(function() {
var count=0;
var right_cols = jQuery(this).find("td:nth-child(1)");
jQuery('#attendee01 tr:visible').each(function() {
var row = jQuery(this);
var left_cols = jQuery(this).find("td:nth-child(3)");
if (left_cols.html() == right_cols.html()) {
count++;
}
});
right_cols.css('color', 'red');
right_cols.append(" <b>" + count + "</b>");
});
}
});

但是,这不是最有效的方法,因为您要循环访问每个m组织的n与会者,从而使时间复杂度O(n*m)。相反,您可以通过只循环一次与会者来使其线性化,同时统计组织总数。然后,您可以只遍历组织一次,并提取那些已经计算过的计数:

jQuery(document).ready(function() {
const counts = {};
jQuery('#attendee01 tr:visible').each(function() {
const org = jQuery(this).find("td:nth-child(3)").text();
counts[org] = (org in counts) ? (counts[org] + 1) : 1;
});
jQuery('#org01 tr').each(function() {
const right_col = jQuery(this).find("td:nth-child(1)");
const org = right_col.text();
const count = counts[org] || 0;
right_col
.css('color', 'red')
.append(" <b>" + count + "</b>");
});
});

最新更新