javascript - 嵌套 double each() 和$(this)

标签 javascript jquery html loops

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

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

我想检查是否 href来自第二个循环(克隆)的项目等于 href来自第一个循环的项目 (menu_items)。 检查来自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的第二个参数,如CertainPerformance所述:

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

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

关于javascript - 嵌套 double each() 和$(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624681/

相关文章:

html - Bootstrap,如何使两个表相同 "width"

javascript - setAttribute 和 getAtttribute 不起作用

javascript - DataTables.js 对包含带有整数文本的 HTML 链接的列进行排序

javascript - Vuex:如何定义一个状态变量,其值基于另一个状态变量的值?

javascript - Uncaught ReferenceError : $ is not defined on DataTable

javascript - 如何在文本区域为空时删除元素?

html - 删除嵌套 CSS flex 上的自动高度分布?

javascript - 有没有更好的方法通过 Javascript for Automation (JXA) 将新播放列表添加到 iTunes?

javascript 新的正则表达式动态

jquery - .hover(...) 等等。 ("hover"...) 行为不同