$('elems')。each()与胖箭头 [英] $('elems').each() with fat arrow

查看:138
本文介绍了$('elems')。each()与胖箭头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用ES6胖箭头函数符号,我真的很喜欢它。但是我对它的上下文有些困惑。据我所知,关键字这里面的胖箭头函数是指函数当前正在运行的上下文。我想做一些简单的jQuery迭代,如:

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

但显然这段代码不工作。如何在胖箭头功能中引用此特定代码中的当前LI元素?



谢谢。

解决方案

each()方法为回调函数提供两个参数。它们是当前索引和当前项。因此,您可以执行以下操作:

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

其中v变量是当前的li元素


I started to use ES6 fat arrow function notation and I really like it. 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. I wanted to do some simple jQuery iteration like:

$('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?

Thank you.

解决方案

The each() method supplies two parameters to the callback-function. 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

这篇关于$('elems')。each()与胖箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆