我想通过读取包含可变数目的对象的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中有什么办法来获取调用它的元素的关键?
我希望有一个明显的解决方案,我只是俯瞰 - 任何帮助非常感谢!
谢谢!
第一个解决方案不适合我,虽然也许我实施它不正确。第二个是在我为每个设置了ID属性之后。谢谢您的帮助! –