This question already has answers here:
How to access the correct `this` inside a callback?
(11个答案)
9个月前关闭。
我有两个数组:
我想检查第二个循环(克隆)的项目中的
从
或者使用
(11个答案)
9个月前关闭。
我有两个数组:
menu_items
和clones
,并且我有两个嵌套的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>
}
});
});