2012-12-03 23 views
2

我想通过读取包含可变数目的对象的xml来减少网页上的代码大小。在javascript代码中,我创建一个数组来保存每个对象,并通过xml数据循环来创建每个对象。有什么办法来获得调用函数的数组元素的键值?

我循环通过xml节点的数量来创建许多对象和对象函数(mouseover,onclick等),但在函数中我使用相同的索引变量来访问当前的对象属性,但是当函数是实际上调用该索引变量不再处于我的范围内。

有没有反正我可以得到调用对象的键(索引)值?

for(index=0, index < scenes.length; index+=1) 
{ 
this.thumbs[index] = document.createElement('div'); 
//setup more properites 
this.thumbs_image[index] = document.createElement('img'); 
//more setup 
this.thumbs[index].onmouseover = function(){ 
me.thumbs_image[index].src = scenes[index].attributes.getNamedItem("src").nodeValue;  //THIS IS THE PROBLEM - WHEN the function is actually called index is no longer the correct index of the array element 
} 
} 

功能之外的代码的onmouseover工作,和它的作品,如果我硬编码的onmouseover中的索引。

我试图创建具有作为参数传入的索引一个单独的功能,但是当我分配的功能动态我仍然指标分配为我想不出的另一种方式,这不工作之一:

this.thumb[index].onmouseover = myFunction(index); 

myFunction=function(i){ 
me.thumbs_image[i].src = scenes[i].attributes.getNamedItem("src").nodeValue; 
} 

在onmouseover中有什么办法来获取调用它的元素的关键?

我希望有一个明显的解决方案,我只是俯瞰 - 任何帮助非常感谢!

谢谢!

回答

0

解决方案一:替换此:

this.thumbs[index].onmouseover = function(){ 
    me.thumbs_image[index].src = scenes[index].attributes.getNamedItem("src").nodeValue; 
} 

与此:

this.thumbs[index].onmouseover = (function(i) { 
    return function() { 
    me.thumbs_image[index].src = scenes[index].attributes.getNamedItem("src").nodeValue; 
    }; 
})(i); 

功能包装将捕获在一个封闭的可变i的价值,让您可以访问值(而不是不存在的变量i)在处理程序被调用时。

第二种解决方案:onmouseover(和所有其他事件处理程序)将收到一个参数,这是事件。该事件知道它起源于何处。试试这个:

this.thumbs[index].onmouseover = function(evt) { 
    console.log(evt.target); 
} 

我建议在这个特殊的情况下,第二个解决方案,但在第一个解决方案的模式是很重要的了解 - 从不创建直接在循环依赖于循环计数器功能,而不是总是有一个函数调用来取代循环计数器的值。

+0

第一个解决方案不适合我,虽然也许我实施它不正确。第二个是在我为每个设置了ID属性之后。谢谢您的帮助! –

相关问题