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

[CHINESE]  带有ES6箭头函数的jQuery .each()函数[重复]


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?

我有这个ES6代码,在我用Babel编译它到ES5里面之后.each的回调变得不确定。我该如何解决这个问题?

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

2 个解决方案

#1


30  

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.

我的解决方案是根本不使用它,而是使用传递给回调函数的变量。第一个是索引,第二个是DOM元素本身。

 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


22  

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,

箭头函数捕获封闭上下文的this值,

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

each()函数将元素作为回调的第二个参数传递。

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

但是更合适的解决方案是使用.map()而不是每个()

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

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号