.on('click')只能使用一次

时间:2015-04-01 15:13:31

标签: javascript jquery html

我尝试使用不同颜色的图块填充div,为此我有一个带有<div id="field">的HTML,以及以下javascript代码:

// I want field to be globally accessible 
var field;
var colors;
$(document).ready(function(){
 field = [[],[],[],[],[],[],[],[],[]];  
 colors =["black","yellow","blue","green","grey","brown"];          
fillField();            


$(".tile").on('click', function(){
console.log("sfadfd");
var x = this.getAttribute("data-x");
var y = this.getAttribute("data-y");
console.log("X: "+x+", Y: "+y);
tileClicked(x,y);
});

});

var tileClicked = function(x,y){
console.log(colors[field[y][x]]);
field[y][x] = 0;
showField();

};

// Displays the field into a neat grid with pretty colors
var showField = function(){
console.log("Test");

$(".tile").remove();

    for (var i = 0; i<field.length; i++){
        for (var j = 0; j<10; j++){
            var color = colors[field[i][j]];

            $("#field").append("<div data-x="+j+" data-y="+i+" class=tile style=background-color:"+color+" ></div>");

            }
console.log("Test3");
            }
}

// Fills empty slots in the field
var fillField = function(){
    for (var i = 0; i<field.length; i++){
        for (var j = 0; j<10; j++){
        var next = Math.floor(Math.random()*5+1);

        if(next == field[i][j-1] ){
        field[i][j] = Math.floor(Math.random()*5+1);
        }
        else { field[i][j] = next;}
        }
    }
showField();
}

问题是它只删除并显示一次瓷砖,我认为它与append()和remove()有关,但我无法弄清楚是什么错误的< / p>

谢谢!

1 个答案:

答案 0 :(得分:2)

使用事件委派,因为您删除了元素(.tile)并动态添加

$("#field").on('click', '.tile' ,function(){

});