我有这个 ES6 代码,在我用 Babel 将其编译为 ES5 后,this
里面.each
的回拨变成undefined
。我该如何解决这个问题?
let mediaBoxes = $(".now-thumbnail");
let titles = [];
mediaBoxes.each(() => {
let obj = {
index: i,
title: $(this).find(".now-thumbnail-bottomtext").text().trim()
};
titles.push(obj);
});
最佳答案
我的解决方案是根本不使用this
,而是使用传递给回调函数的变量。第一个是索引,第二个为您提供 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);
});
关于javascript - 带有 ES6 箭头函数的 jQuery .each() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36638002/