0
$('#stuff_btn').on('click', function(event){
event.preventDefault();

$(this).remove();
$('#stuff').prepend('<div id="current_lvl">Level: 1</div>');

var words = ["arvuti","pudel","ekraan"];
var random = Math.floor(Math.random() * words.length);
var word = words[random];   
var chars = word.split('');
chars = _.shuffle(chars);

for(var i in chars)
{
    $('#word_place_grid ul').append('<li id="letter' + i + '">' +  chars[i] +  '</li>');

    $('#letter'+i).bind('click',function(){
        $(this).animate({
            opacity: 0.30,
            top: -55,
        },750,function(){    //Animation complete
            $('#game_window_grid ul').append('<li>' + chars[i] + '</li>');
            $(this).remove();
        });
    });
}

})

HTML:

    <div class="word_grid" id="game_window_grid">
    <ul>
    </ul>
</div>

<div class="word_grid" id="word_place_grid">
    <ul>
    </ul>
</div>

So I am trying to take a word randomly from the list. Shuffle the letters. Put each letter to a separate li in the dic #word_place_grid. Then I wan to add the click handler to each div that would animate that li and in the end of the animation I would like to add the value of the animated li to a new li element that I append to the div #game_window_grid. The problem is that with the jQuery code I have right now, it will add the last random character from the list: chars to all of the li elements that I add to the div #game_window_grid. No matter which way I try to rewrite the code, I still cant get the right value for li.

Any idea what I should change or what should I do to get the correct value for the div #game_window_grid li ?

Thanks in advance

4

1 回答 1

1

把这个拔出来...

$('#letter'+i).bind('click',function(){
    $(this).animate({
        opacity: 0.30,
        top: -55,
    },750,function(){    //Animation complete
        $('#game_window_grid ul').append('<li>' + chars[i] + '</li>');
        $(this).remove();
    });
});

把这个放在别的地方...

$('#word_place_grid').on('click', '[id^=letter]', function(){
  var character = $(this).text();
    $(this).animate({
        opacity: 0.30,
        top: -55,
    },750,function(){    //Animation complete
        $('#game_window_grid ul').append('<li>' + character + '</li>');
        $(this).remove();
    });
});

编辑:或者,您可以摆脱 for...in 循环并替换$.each()为您的迭代器

$.each(chars, function(i, character) {
  $('#word_place_grid ul').append('<li id="letter' + i + '">' +  character +  '</li>');
  $('#letter'+i).on('click',function(){
      $(this).animate({
          opacity: 0.30,
          top: -55,
      },750,function(){    //Animation complete
          $('#game_window_grid ul').append('<li>' + character + '</li>');
          $(this).remove();
      });
  });
});

PS.bind()不像 jQuery 1.7 那样被广泛使用,它.on()包含相同的功能,并增加了页面加载后可能发生的委托事件的好处(这就是我原来的答案如何找到动态添加的元素[id^=letter]

于 2013-09-17T19:30:41.460 回答