2014-04-03 72 views
0

我在寫一個小型JavaScript遊戲。將onmouseover事件綁定到數組中的多個元素

我看的代碼對應的位:

cells[i].onmouseover = function() { 
     cells[i].style.top = 
     (cells[i].getAttribute('data-top') - 25).toString() + "px"; 
    } 

每個細胞[I]元素是<img>元件陣列的成員。

目前,每當我將鼠標懸停在一個img元素會生成以下錯誤:

Uncaught TypeError: Cannot read property 'style' of undefined 

我不知道是什麼回事。爲什麼cells[i]未定義?

這裏的所有可能相關的代碼:

for(var i = 0; i < mapSize; ++i) { 
    cells[i] = document.createElement('img'); 
    cells[i].src = 'base1.png'; 
    cells[i].class = 'base1'; 
    cells[i].id = 'cell' + i; 

    game.appendChild(cells[i]); 

    row = Math.floor(i/mapWidth); 

    top = tops[i%mapWidth + row]; 
    left = lefts[mapWidth + (i % mapWidth) - row]; 

    cells[i].setAttribute('data-top',top); 
    cells[i].setAttribute('data-left',left); 

    cells[i].style.top = top.toString() + "px"; 
    cells[i].style.left = left.toString() + "px"; 
    cells[i].style.zindex = i; 

    console.log(cells[i]); 

    cells[i].onmouseover = function() { 
     cells[i].style.top = 
     (cells[i].getAttribute('data-top') - 25).toString() + "px"; 
    } 
} 
+1

閱讀DUP知道發生了什麼,但我建議你使用事件代表團。 – elclanrs

+0

謝謝!這很有趣。 – JimmyM

+2

請注意'onclick'只支持單個事件功能。 'addEventListener'允許將多個事件附加到一個元素上。 –

回答

-3

這應該工作...

cells.each(function(key, index){ 
    var _this = $(this); 
    _this.mouseover(function() { 
     var top = _this.data("top") - 25; 
     $(this).css("top",top); 
    }); 
}) 
+2

這個神奇的jQuery來自哪裏..? –

+2

哦,而且,「這應該工作」不是一個很好的解釋你的代碼。 –

+2

更不用說它不正確的使用'.data()',或者你自己的代碼顯示'_this'變量是不必要的。 –

相關問題