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

标签 javascript jquery

我已经修改了以下代码以适合我的文档,并且它有效,但我不明白为什么它使用 .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/

相关文章:

javascript - 将参数传递给事件函数

javascript - 使用正则表达式转义单词开头和冒号之间的特殊字符

jquery - 表单验证与隐藏字段结合使用

javascript - 在没有嵌套函数的情况下跟踪 javascript 回调的完成

javascript - 当我使用浏览器后退按钮时保持 javascript 更改(jquery,rails 3)

javascript - 添加图像链接

jquery - 使用 jQuery 设置表单提交的值

javascript - Flipclock.js 间隔回调方法,每分钟触发一个事件

javascript - 我可以找到与此设计类似的日期选择器库吗?

javascript - JQuery 工具提示位置