为什么 .each 与 jQuery 选择器一起使用,然后再与 $(this) 一起使用



我有以下一段代码,我已经修改了以适应我的文档,它可以工作,但我不明白为什么它使用 .each 两次? 我在下面代码中的注释应该显示我感到困惑的地方。

function searchFunction(value) {
//This cycles through each tr and runs the function
$('#results tr').each(function() {
var found = 'false';
//$(this) then selects the tr and then runs through each tr (again!) for the If statement.    
$(this).each(function() {
if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
found = 'true';
}
});
if (found === 'true') {
$(this).show();
} else {
$(this).hide();
}
});
};

我尝试删除第二个 .each,但代码中断。任何帮助将不胜感激!

谢谢!

内部$(this).each(...)实际上将循环由一个tr元素组成的集合。因此,在这种情况下它是完全多余的,可以删除第二个each()

可能一开始的想法是遍历每行中的每个单元格,有点像:

$('#results tr').each(function() {
$(this).find('td').each(function() {
//...
});
});

但是您不能随机隐藏/显示单元格,因为这会破坏表格布局。可能是作者明白了,并删除了.find('td')件:)只是一个假设...

最新更新