将事件添加到数组的元素

时间:2011-11-11 18:09:10

标签: javascript

我试图在数组中创建一个循环,并向其元素添加事件,而不是成功。 这是数组:

div_empresa_links_elements.push({
    div_mouseover: div_imagens_mouseover,
    div_submenu: div_empresa_imagens,
    div_txt: div_imagens_txt
}, {
    div_mouseover: div_institucional_mouseover,
    div_submenu: div_empresa_institucional,
    div_txt: div_institucional_txt
}, {
    div_mouseover: div_localizacao_mouseover,
    div_submenu: div_empresa_localizacao,
    div_txt: div_localizacao_txt
}, {
    div_mouseover: div_infraestrutura_mouseover,
    div_submenu: div_empresa_infraestrutura,
    div_txt: div_infraestrutura_txt
}, {
    div_mouseover: div_politicaDeQualidade_mouseover,
    div_submenu: div_empresa_politicaDeQualidade,
    div_txt: div_politicaDeQualidade_txt
}, {
    div_mouseover: div_linhaDoTempo_mouseover,
    div_submenu: div_empresa_linhaDoTempo,
    div_txt: div_linhaDoTempo_txt
}, {
    div_mouseover: div_historico_mouseover,
    div_submenu: div_empresa_historico,
    div_txt: div_historico_txt
})

这是循环:

for (var i = 0; i < div_empresa_links_elements.length; i++) {
    var obj = div_empresa_links_elements[i]
    obj.div_mouseover.onmouseover = function () {
        obj.div_txt.style.opacity = 1
        obj.div_txt.style.filter = 'alpha(opacity = 100)'
        obj.div_submenu.style.opacity = .7
        obj.div_submenu.style.filter = 'alpha(opacity = 70)'
    }
}

如果我在没有循环的情况下手动为每个元素(_mouseover)放置一个事件,那么事情就行了。谁能告诉我为什么?

1 个答案:

答案 0 :(得分:3)

问题是由关闭问题引起的。目前,每次迭代都会覆盖obj。因此,obj指向最后定义的元素。要解决此问题,请将循环的主体包装在自调用函数中,并将变量obj作为参数传递,如下所示:

 for (var i = 0; i<div_empresa_links_elements.length;i++){
    var obj = div_empresa_links_elements[i]
    (function(obj){ //obj is declared again. Inside this func, obj = <see below>
        obj.div_mouseover.onmouseover = function(){
            obj.div_txt.style.opacity = 1
            obj.div_txt.style.filter = 'alpha(opacity = 100)'
            obj.div_submenu.style.opacity = .7
            obj.div_submenu.style.filter = 'alpha(opacity = 70)'
        }
    })(obj); //Pass the variable obj as defined at the top
}