【问题标题】:Is there any way to get the key value of the array element that called a function?有什么方法可以获取调用函数的数组元素的键值吗?
【发布时间】:2012-11-20 12:12:59
【问题描述】:

我试图通过读取包含可变数量对象的 xml 来减少网页上的代码大小。在 javascript 代码中,我创建了一个数组来保存每个对象并循环通过 xml 数据来创建每个对象。

我循环遍历 xml 节点的数量以创建那么多对象和对象函数(鼠标悬停、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 中是否有任何方法可以获取调用它的元素的键?

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

谢谢!

【问题讨论】:

    标签: javascript arrays dynamic key


    【解决方案1】:

    第一个解决方案:替换这个:

    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);
    }
    

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

    【讨论】:

    • 第一个解决方案对我不起作用,尽管我可能实施不正确。第二个是在我为每个设置 ID 属性后完成的。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多