来自bind的意外行为

时间:2013-02-14 03:56:12

标签: jquery

我没有获得点击绑定,而是获得了一个控制台消息列表,好像Javascript正在执行绑定操作而不是创建绑定:

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)
      });
    });
});

3 个答案:

答案 0 :(得分:3)

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

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

$('div#terrainGuide:last-child').bind({
    click: function(){
       changeTerrain(biome);
    }
});

答案 1 :(得分:1)

你必须在绑定调用中使用匿名函数,即:

 click: changeTerrain(biome)

应该成为

 click: function(){ changeTerrain(biome); }

答案 2 :(得分: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);
});