$('#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>
所以我试图从列表中随机抽出一个字。洗牌。将每个字母放在dic #word_place_grid中的单独li中。然后我想将click处理程序添加到每个div中,它将为li设置动画,并且在动画结束时我想将动画li的值添加到我追加到div #game_window_grid的新li元素中。 问题是,使用我现在拥有的jQuery代码,它将添加列表中的最后一个随机字符:chars到我添加到div #game_window_grid的所有li元素。无论我尝试重写代码的哪种方式,我仍然无法为li获得正确的价值。
知道我应该改变什么或者我该怎么做以获得div的正确值#game_window_grid li?
提前致谢
答案 0 :(得分: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();
});
});
});
P.S。 .bind()
不像jQuery 1.7那样被广泛使用.on()
包含相同的功能,并且在加载页面后可能会发生委托事件的额外好处(这是我的原始答案如何动态查找添加了元素[id^=letter]