带有ES6箭头功能的jQuery .each()函数 [英] jQuery .each() function with ES6 arrow functions

查看:302
本文介绍了带有ES6箭头功能的jQuery .each()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个ES6代码,在我用Babel编译它到ES5之后这个里面的 .each 's回拨变为 undefined 。我该如何解决这个问题?

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);
});


推荐答案

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

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);
 });

这篇关于带有ES6箭头功能的jQuery .each()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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