jQuery .each() function with ES6 arrow functions [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:46:02

问题:

This question already has an answer here:

I have this ES6 code, after I compile it with Babel to ES5 the this inside .each's call back becomes undefined. How do I fix this problem?

let mediaBoxes = $(".now-thumbnail"); let titles = []; mediaBoxes.each(() => {       let obj = {               index: i,               title: $(this).find(".now-thumbnail-bottomtext").text().trim()            };   titles.push(obj); }); 

回答1:

My solution is to not use this at all, but use the variables that are passed to the callback function. The first one is the index and the second one gives you the DOM element itself.

 let mediaBoxes = $(".now-thumbnail");  let titles = [];  mediaBoxes.each((index, element) => {                 let obj = {                     index: index,                     title: $(element).find(".now-thumbnail-bottomtext").text().trim()                 };                 titles.push(obj);  }); 


回答2:

That is because the mean of this is not the same in arrow functions.

this

Arrow functions capture the this value of the enclosing context,

The each() function passes the element as the second argument to the callback.

But a more appropriate solution for you will be to also use .map() instead of each()

let mediaBoxes = $(".now-thumbnail"); let titles = mediaBoxes.map((i, el) => {   return {     index: i,     title: $(el).find(".now-thumbnail-bottomtext").text().trim()   }; }).get(); 


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