javascript - .on('click') only works once -


this question has answer here:

i'm trying fill div different color tiles, have html <div id="field">, , following javascript code:

// want field 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 field neat grid pretty colors var showfield = function(){ console.log("test");  $(".tile").remove();      (var = 0; i<field.length; i++){         (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 field var fillfield = function(){     (var = 0; i<field.length; i++){         (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(); } 

the problem removes , displays tiles once, think has append() , remove(), can't figure out what's wrong

thanks!

use event delegation beacuse remove element(.tile) , add dynamically

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

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -