Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...