This question already has answers here:
How to access the correct `this` inside a callback?
                            
                                (11个答案)
                            
                    
                9个月前关闭。
        

    

我有两个数组:menu_itemsclones,并且我有两个嵌套的each()函数。

$(menu_items).each(function() {
  $(clones).each(function() {
    if ($(this).attr("href") == ...) {
        <do sth>
    }
  });
});


我想检查第二个循环(克隆)的项目中的href是否等于第一个循环(menu_items)的项目中的href
clones检查项目很容易:$(this).attr("href")。但是第一次循环menu_items怎么办? $(this).$(this).attr("href")?我想不是:(请帮助。

最佳答案

您可以将this引用保存在外部循环中,以在内部循环中使用它:

$(menu_items).each(function() {
  const outerThis = $(this);

  $(clones).each(function() {
    if ($(this).attr("href") == outerThis.attr('href')) {
        <do sth>
    }
  });
});


或者使用.each的第二个参数,如SomePerformance所述:

 $(menu_items).each(function(_, menuItem) {

      $(clones).each(function(_, clone) {
        if (clone.attr("href") == menuItem.attr('href')) {
            <do sth>
        }
      });
    });

08-18 17:30
查看更多