【发布时间】:2016-04-06 20:25:04
【问题描述】:
我卡在 Javascript 的事件处理程序方面。
rowCells[j] 是对唯一对象的引用。 galleryCell 也是对新创建对象的引用。按理说两者可以联系在一起。
但是,这两个引用似乎根本没有绑定在一起以使事件侦听器正常工作。所有单元格都被分配给相同的东西(最后一个 galleryCell 对象)。
galleryCell 变量在一个 for 循环中,在每次迭代时都会获得一个新的引用。为什么这些引用会丢失?
function TypeGallery (galleryObj)
{ //receives the <div> element that contains rows and cells of a gallery
//Properties --------------
var galleryCellArr = []; //array of galleryZoomCell objects
//Methods -----------------
var Initialize = function ()
{
var rows = galleryObj.children;
var rowCount = rows.length;
for (var i=0;i<rowCount;i++)
{
var rowCells = rows[i].children;
var rowCellCount = rowCells.length;
for (var j=0;j<rowCellCount;j++)
{
var sliderObj = new TypeSlider(300,1,false);
var galleryCell = new TypeGalleryZoomCell(rowCells[j],sliderObj)
galleryCellArr.push(galleryCell);
rowCells[j].onmousedown = function () {galleryCell.Deploy();};
rowCells[j].onmouseup = function () {galleryCell.Retract();};
}
}
}
//Initialization
Initialize();
}
【问题讨论】:
-
galleryCell 变量的作用域不是 for 块,而是整个 Initialize 函数。因此,每次迭代都会完全重写它,因此当事件触发时,调用的函数只是 galleryCell 的最新分配。看看stackoverflow.com/questions/750486/…
标签: javascript