for循环中的jQuery mouseover()函数赋值不正确

时间:2015-12-30 16:45:36

标签: javascript jquery

问题在于:

for(i=0;i<grid.length;i++)
{
    for(j=0;j<grid[i].length;j++)
    {
        console.log(current_grid);
        var current_grid = grid[i][j];
        current_grid.bgc("red");
        current_grid.dom.mouseover(function()
        {
            console.log(current_grid.ident);
        });
    }
}

console.log始终返回循环中的最后一个元素。所以这是完整的代码,鼠标悬停时的输出始终是“td_3_3”。

function main(){

var canvas = new Element('body','canvas','div','absolute');
canvas.fullscreen();
canvas.bgc("red");

var tablet = new Element('#canvas','tablet','table','relative');
tablet.fullscreen();
canvas.bgc("black");
tablet.dom.css("table-layout","fixed");

var row_1e = new Element('#tablet','row_1e','tr','');
var td_1_1 = new Element('#row_1e','td_1_1','td','');
var td_2_1 = new Element('#row_1e','td_2_1','td','');
var td_3_1 = new Element('#row_1e','td_3_1','td','');

var row_2e = new Element('#tablet','row_2e','tr','');
var td_1_2 = new Element('#row_2e','td_1_2','td','');
var td_2_2 = new Element('#row_2e','td_2_2','td','');
var td_3_2 = new Element('#row_2e','td_3_2','td','');


var row_3e = new Element('#tablet','row_3e','tr','');
var td_1_3 = new Element('#row_3e','td_1_3','td','');
var td_2_3 = new Element('#row_3e','td_2_3','td','');
var td_3_3 = new Element('#row_3e','td_3_3','td','');

var row_1 = [td_1_1,td_2_1,td_3_1],
    row_2 = [td_1_2,td_2_2,td_3_2],
    row_3 = [td_1_3,td_2_3,td_3_3];

var grid = [row_1,row_2,row_3];

for(i=0;i<grid.length;i++)
{
    for(j=0;j<grid[i].length;j++)
    {
        console.log(current_grid);
        var current_grid = grid[i][j];
        current_grid.bgc("red");
        current_grid.dom.mouseover(function()
        {
            console.log(current_grid.ident);
        });
    }
}
}

function Element(myparent,ident,type,position)
{
this.ident=ident;
this.myparent = myparent;
this.html5 = '<'+type+' id='+this.ident+'></'+type+'>';
this.dom = this.draw_element();
if (position != '')
{
    this.dom.css("position",position);
}
}

Element.prototype.draw_element = function()
{
$(this.myparent).append(this.html5);
return $('#'+this.ident);
}

Element.prototype.fullscreen = function()
{
this.position("0","0");
this.resize("100%","100%");
}

Element.prototype.bgc = function(color)
{
this.dom.css('background-color',color);
}

Element.prototype.position = function(x,y)
{
this.dom.css({'left':x,'top':y});
}

Element.prototype.resize = function(x,y)
{
this.dom.css({'width':x,'height':y});
}

1 个答案:

答案 0 :(得分:2)

循环运行时,

current_grid被赋值,循环退出后,current_grid的值是数组中的最后一项。 循环存在后,点击事件

你想要更像这样的东西:

for(i=0;i<grid.length;i++)
{
    for(j=0;j<grid[i].length;j++)
    {
        console.log(current_grid);
        var current_grid = grid[i][j];
        current_grid.bgc("red");
        // you have jQuery, use it
        $(current_grid).click(function(event,ui){
            console.log($(this).id);
        });
    }
}