请参阅以下代码段。
考虑在DOM中有这样的图像。
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350?thumbnail_width=2000&thumbnail_height=500&resize_type=CropToFit" height="500" width="2000" alt="">
从图片中提取src
属性值,如下面的jQuery。
$('img').each(() => {
let curSrc = $(this).attr('src');
console.log("With the arrow function : ");
console.log(curSrc);
});
$('img').each(function() {
let curSrc = $(this).attr('src');
console.log("Regular old school function : ");
console.log(curSrc);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350?thumbnail_width=2000&thumbnail_height=500&resize_type=CropToFit" height="500" width="2000" alt="">
为什么$(this)
或this
指向箭头功能内的window
?