我已经修改了以下代码以适合我的文档,并且它有效,但我不明白为什么它使用 .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')
片段:)只是一个假设......
关于javascript - 为什么 .each 与 jQuery 选择器一起使用,然后又与 $(this) 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59198897/