我有两个数组:menu_items
和clones
,并且我有两个嵌套的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/