JavaScript 无法从函数的数组参数中获取值
JavaScript can't get value off function's array parameter
我正在尝试根据高度对列中的一些图像进行排序,我有以下代码。问题是,即使imgHeights.length工作正常,imgHeights[i](在redrawThumbs函数中)也不会返回值。我做错了什么?谢谢=)
function redrawThumbs(imgHeights){
// some irrelevant code here
// initialise an array that will hold all the column's heights
var colHeights = new Array(cols);
for(a=0; a <= colHeights.length - 1; ++a){
colHeights[a] = 0;
}
// take each image's height and add it to the shortest column
for(i=0; i <= imgHeights.length - 1; ++i){
var shortestCol = 0;
for(c=0; c <= colHeights.length - 2; ++c){
if(colHeights[c+1] < colHeights[c]){
shortestCol = colHeights[c+1];
}
}
alert("imgHeights[" + i + "] " + imgHeights[i]);
colHeights[shortestCol] += imgHeights[i];
}
}
// make an array of image heights
var imgHeights = new Array(totalThumbs);
for(i=1; i <= totalThumbs; ++i){
var img = new Image();
img.onload = function(){
imgHeights[i-1] = this.height;
}
img.src = i + ".jpg";
// call function that orders the images
redrawThumbs(imgHeights);
其中一个
问题是i
变量是通过引用而不是按值捕获的,因此,对于img.onload
的所有回调,都获得了相同的 i
值。请考虑将onload
分配更改为,
var loadedCount = 0;
img.onload = (function (i) {
return function () {
imgHeights[i - 1] = this.height;
if (++loadedCount == totalThumbs) allLoaded();
};
})(i);
function allLoaded() {
// called after all the images have been loaded.
}
这会在自动执行函数执行时捕获 i
值的副本,并在加载所有图像后调用allLoaded()
。
相关文章:
- jqGrid - 将表单数据提交到 jqGrid,并让 jqGrid 使用这些参数获取数据
- 使用add:true参数获取集合时,重新渲染主干视图
- 我对javascript中的一个自定义函数感到困惑,该函数将对象作为参数获取
- 使用 javascript 或 Meteor 中的函数参数获取对象值
- 使用 colModel 网格参数获取占位符的值
- 如何使用要作为参数获取和传递的元素的 id 在元素中查找元素
- 如何通过参数获取Chrome本地存储结果的值映射
- 通过窗口点击参数获取请求
- 正在从参数获取变量
- 参数获取方法是这样正确还是错误
- 从URL参数获取值
- 使用Javascript从url参数获取一个变量
- 如何从集合中通过数组参数获取模型
- js无法使用日期范围查询参数获取新创建的用户
- (Angular JS)如何过滤$http.如果响应是JSON对象数组,则通过传递参数获取
- 为NEW objects参数获取HTML输入范围值
- 通过javascript对象的参数获取/查找该对象
- 从对象参数获取 jquery 选择器
- 在java中使用Get参数获取所有值
- 用谓词表达式作为参数获取api请求