这不是一个重复的问题。我一直在完成页面加载后加载图像。我想要将变量i
值传递给img的onload
函数,但不知何故,这不起作用。通过变量在Javascript中运行
var imgs = document.getElementsByTagName('img');
var totalImages = imgs.length;
for(var i=0; i<totalImages; i++)
{
if(imgs[i].hasAttribute('data-src'))
{
var img = new Image();
img.onload = function()
{
imgs[x].src = imgs[x].getAttribute('data-src');
imgs[x].setAttribute('srcLoaded','true');
//where x is i value from for loop
};
img.src = imgs[i].getAttribute('data-src');
}
}
我尝试下面的onload功能
img.onload = (function(x)
{
imgs[x].src = imgs[x].getAttribute('data-src');
imgs[x].setAttribute('srcLoaded','true');
//where x is i value from for loop
})(i);
,但这样一来,我看到了,立即执行该功能即使图像不完全加载可能是因为这是某种工作作为匿名函数。
我还通过设置属性来我img
对象,并进入内部功能的价值这样
img.setAttribute('idi',i);
img.onload = function()
{
var x = img.getAttribute('idi');
imgs[x].src = imgs[x].getAttribute('data-src');
imgs[x].setAttribute('srcLoaded','true');
//where x is i value from for loop
};
尝试,但无法运作为好。如何将变量i
的值传递给我的onload函数?
IIFE必须返回一个函数,如'img.onload =(function(x){return(){img [x] .src = imgs [x] .getAttribute('data-src'); imgs [ x] .setAttribute('srcLoaded','true'); //其中x是来自for循环的i值 } })(i);' –
但它仍然是onl一个函数,因为它在每次迭代中被覆盖。 –
@ArunPJohny我已经提到你的建议方式不起作用。 –