如何在嵌套函数中获取 $(this)
How to get $(this) in nested function
我想在图像完全加载后显示它来实现这个东西,我尝试编写一些代码从图像中获取 data-src
并将其添加到新的 Image 对象中,加载该对象后,它应该将 image src
替换为 object src
但是有一个问题,在嵌套函数中 $(this)
不起作用它只得到最后一张图片这里是代码...
$('li img').each(function(){
timg = $(this);
var k = new Image();
k.src = $(timg).data('src');
$(k).load(function(){
console.log (k.src);
$(timg).attr('src', k.src);
//timg [$(This)] is not working;
});
});
使用 Function.bind() 明确告诉你的 neastead 函数你希望谁成为它的 this
变量:
$('li img').each(function(){
var k = new Image();
k.src = $(this).data('src');
$(k).load(function(){
console.log (k.src);
$(this).attr('src', k.src);
console.log(this); // Shall work now
}.bind(this));
});
更多详情:
// First case
function MyTest() {
setTimeout(function() {
console.log(this); // will log [object Window]
});
}
// Second case
function MyTest() {
setTimeout(function() {
console.log(this); // will log "anything"
}.bind("anything"));
}
// Another case
function MyTest() {
setTimeout(function() {
console.log(this); // will log [object Object] (MyTest)
}.bind(this));
}
看这个Example
您的 timg
已经 jQuery obj,因此您不需要任何转换。您还使用全局变量 timg
所以它在每次循环迭代中都会改变,所以只需使用 local.
$('li img').each(function(){
var timg = $(this);
var k = new Image();
k.src = timg.data('src');
$(k).load(function(){
console.log (k.src);
timg.attr('src', k.src);
});
});
我想在图像完全加载后显示它来实现这个东西,我尝试编写一些代码从图像中获取 data-src
并将其添加到新的 Image 对象中,加载该对象后,它应该将 image src
替换为 object src
但是有一个问题,在嵌套函数中 $(this)
不起作用它只得到最后一张图片这里是代码...
$('li img').each(function(){
timg = $(this);
var k = new Image();
k.src = $(timg).data('src');
$(k).load(function(){
console.log (k.src);
$(timg).attr('src', k.src);
//timg [$(This)] is not working;
});
});
使用 Function.bind() 明确告诉你的 neastead 函数你希望谁成为它的 this
变量:
$('li img').each(function(){
var k = new Image();
k.src = $(this).data('src');
$(k).load(function(){
console.log (k.src);
$(this).attr('src', k.src);
console.log(this); // Shall work now
}.bind(this));
});
更多详情:
// First case
function MyTest() {
setTimeout(function() {
console.log(this); // will log [object Window]
});
}
// Second case
function MyTest() {
setTimeout(function() {
console.log(this); // will log "anything"
}.bind("anything"));
}
// Another case
function MyTest() {
setTimeout(function() {
console.log(this); // will log [object Object] (MyTest)
}.bind(this));
}
看这个Example
您的 timg
已经 jQuery obj,因此您不需要任何转换。您还使用全局变量 timg
所以它在每次循环迭代中都会改变,所以只需使用 local.
$('li img').each(function(){
var timg = $(this);
var k = new Image();
k.src = timg.data('src');
$(k).load(function(){
console.log (k.src);
timg.attr('src', k.src);
});
});