有没有办法获取调用函数的数组元素的键值?

时间:2012-12-03 02:19:35

标签: javascript arrays dynamic key

我试图通过读入包含可变数量对象的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中是否有任何方法可以获取调用它的元素的键?

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

谢谢!

1 个答案:

答案 0 :(得分: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);
}

我建议在这种特殊情况下使用第二种解决方案,但第一种解决方案中的模式非常重要 - 永远不要在循环中直接创建依赖于循环计数器的函数,而是始终使用函数调用来捕获循环反而是反价值。