$('elems').each() with fat arrow

こ雲淡風輕ζ 提交于 2019-11-26 14:35:21

问题


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?


回答1:


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




回答2:


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

$('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');


来源:https://stackoverflow.com/questions/36548683/elems-each-with-fat-arrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!