简体   繁体   English

$('elems')。每个()带有胖箭头

[英]$('elems').each() with fat arrow

I started to use ES6 fat arrow function notation and I really like it. 我开始使用ES6胖箭头功能表示法,我非常喜欢它。 But I am a little bit confused about it context. 但我对它的背景有点困惑。 As far as I know, keyword this inside fat arrow function refers to context where the function is currently running. 据我所知,关键字this fat arrow函数指的是函数当前运行的上下文。 I wanted to do some simple jQuery iteration like: 我想做一些简单的jQuery迭代,如:

$('ul#mylist > li').each(() => {
   $(this).addClass('some-class-name');
});

But obviously this piece of code not working. 但显然这段代码不起作用。 How do I refer, inside fat arrow function, to current "LI" element in this specific code? 如何在胖箭头函数中引用此特定代码中的当前“LI”元素?

The each() method supplies two parameters to the callback-function. each()方法为回调函数提供两个参数。 They are current index and the current item. 它们是当前索引和当前项目。 Thus you could do the following: 因此,您可以执行以下操作:

$('ul#mylist > li').each((i, v) => {
   $(v).addClass('some-class-name');
});

Where the "v" variable is the current "li" element 其中“v”变量是当前的“li”元素

Because this in the arrow function context is the same as the calling context. 因为这个箭头功能方面是一样的调用上下文。

The each function provides a current element as the second argument to the callback so each函数都提供一个当前元素作为回调的第二个参数

$('ul#mylist > li').each((i, el) => {
  $(el).addClass('some-class-name');
});

Or in the given case there is no need to loop 或者在给定的情况下,不需要循环

$('ul#mylist > li').addClass('some-class-name');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM