如何将变量与函数动态绑定
How to dynamically bind variable with a function?
问题:当image.onload事件下载并检测到新图像时,必须动态更改以前加载的图像。比如说,picture1.png下载并立即更改,picture2.png下载后立即更改,依此类推。我试过下面的方法,但没有成功:
<script type="text/javascript">
loadImage = function(){
var imgs = new Array();
var IMG = document.getElementsByTagName('img');
for(var i=1;i<=IMG.length;i++)
{
imgs[i] = new Image();
imgs[i].src = "picture" + i + ".png";
imgs[i].onload = function(){
alert('picture'+i+' loaded');
IMG[i].setAttribute('src',imgs[i].getAttribute('src'));
}
}
}
</script>
<img src="sample.png" />
<img src="sample.png" />
<img src="sample.png" />
<img src="sample.png" />
<input type="button" value="Load Image" onclick="loadImage()">
事情将如何以期望的方式发生?
使用closure
,因为onload
事件是异步的。onload
处理程序中i
的值将是循环的maximum
值,因为当它是invoked
时,循环已经迭代。
function loadImage() {
var temp = ['http://lorempixel.com/400/200/sports/1/', 'http://lorempixel.com/400/200/sports/2/', 'http://lorempixel.com/400/200/sports/3/'];
var IMG = document.getElementsByTagName('img');//Get all the image tag elements from DOM
for (var i = 0; i < IMG.length; i++) { //Loop for all elements selected
var image = new Image();// New Image() object
image.onload = (function(i, image) { // Closure to keep value from loop(i and image) as javascript is having function level scope and using closure, we can keep the value in the memory to be used later
return function() { // return function as a handler of image onload and it will be getting valid(not final) value of the loop(current instance)
alert(image.src);
IMG[i].src = image.src;
}
})(i, image);
image.src = temp[i];
}
}
<img src="http://lorempixel.com/400/200/sports/5/" />
<img src="http://lorempixel.com/400/200/sports/6/" />
<img src="http://lorempixel.com/400/200/sports/7/" />
<input type="button" value="Load Image" onclick="loadImage()">
您可以使用javascript本机"bind"方法来执行此操作。例如:
var fn = function(index){
alert('picture'+ index +' loaded');
this.setAttribute('src',imgs[index].getAttribute('src'));
};
imgs[i].onload = fn.bind(IMG[i], i);
相关文章:
- 将值动态绑定到jquery中的切换按钮
- 注册OpenLayers事件时,即使使用匿名函数或绑定,JavaScript关闭也会触发循环内的所有内容
- 如何使用AnguarJS动态绑定网站数据
- 在extJS 4.2中,有没有一种方法可以将模型值动态绑定到表单
- 为什么prototypjs观察到回调函数有绑定
- 是否可以使用Sinon.JS检查函数参数绑定是否正确
- 我想在ext.js4.2中将树存储动态绑定到树面板中
- 选择与给定函数没有绑定的所有元素
- 如何让 AngularJS 选取在 JavaScript 中创建的动态绑定
- Emberjs - 将参数动态绑定到视图
- 将函数事件绑定到更改函数的复选框/标签
- KnockoutJS删除动态绑定
- jquery验证,动态绑定表单验证
- 如何将变量与函数动态绑定
- jQuery动态绑定文件输入并在函数中检索文件
- 在jQuery上动态绑定函数
- 如何为每个函数动态绑定“this”
- 如何使用模型中的函数表达式将函数动态绑定到ng-click
- jQuery点击函数未绑定到动态更改的类
- 多个元素上的动态绑定处理程序将只调用最后一个绑定函数