2

Rather than getting a click bind, I'm getting a list of console messages, as though Javascript is executing the bind's action right away instead of creating a bind:

var biomes = new Array("glacier","desert","forest","grassland","hills","jungle","mountains","ocean","plains","swamp","tundra");


function changeTerrain(biome){
  console.log(biome);
}

$(document).ready(function(){
  // fill in terrain guide
    $.each(biomes,function(x,biome){
      $('div#terrainGuide').append("<div class='tile "+biome+"'></div>");
      $('div#terrainGuide:last-child').bind({
        click: changeTerrain(biome)
      });
    });
});
4

3 回答 3

3

当您只需要绑定一次时,您似乎将相同的事件处理程序绑定到要附加的所有元素。

$.each(biomes,function(x,biome){
  $('div#terrainGuide').append("<div class='tile "+biome+"'></div>");
});

$('div#terrainGuide:last-child').bind({
    click: function(){
       changeTerrain(biome);
    }
});
于 2013-02-14T04:07:02.000 回答
1

You have to use an anonymous function in the bind call, i.e.:

 click: changeTerrain(biome)

should become

 click: function(){ changeTerrain(biome); }
于 2013-02-14T04:02:55.960 回答
0

我认为您可以通过以下方式获得所需的行为:

var biomes = new Array("glacier","desert","forest","grassland","hills","jungle","mountains","ocean","plains","swamp","tundra");

function changeTerrain(e){
  //gets the clicked child by calling e.target, and an small hack to get the child's biome
  console.log($(e.target).attr('class').split(' ')[1]);
}

$(document).ready(function(){
  // fill in terrain guide
    $.each(biomes,function(x,biome){
      $('div#terrainGuide').append("<div class='tile "+biome+"'>"+biome+"</div>");
    });
   //remove the bind from the loop and binds the click event to all .tile elements, which are #terrainGuide children
   $("div.tile").click(changeTerrain);
});
于 2013-02-14T04:21:39.497 回答