This question already has an answer here:
Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
我的app.js是用es6标准编写的,我的问题是>
如何使用这样的代码?:

$('img').each(() => {
    var title = $(this).attr('src');
    titles.push(title);
});


我观察到该节点将该代码编译为:

'use strict';

$('img').each(function () {
    var title = $(undefined).attr('src');
    titles.push(title);
});


将“ this”编译为“ undefined”,我该如何解决?
提前;)

最佳答案

另一种解决方案是使用传递给回调的元素,如.each文档-函数(整数索引,Element element)中所定义:



var titles = [];

$('img').each((index, element) => {
    var title = $(element).attr('src');
    titles.push(title);
});

document.getElementById('demo').innerHTML = JSON.stringify(titles, undefined, 4);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://38.media.tumblr.com/avatar_502c67b98956_64.png">

<img src="https://s-media-cache-ak0.pinimg.com/favicons/62c7e8f531e824f6f8da34453cdd698a8856f3aea36118408c3e5c09.png?9e884f0299eee37aedab60fe1ed363b5">

<pre id="demo"></pre>

09-25 16:42