我有一個div。 這個div中有一個按鈕清空div並用新內容填充它。jQuery:點擊事件中的點擊事件
問題就出在這裏,當DIV充滿了新的內容,我不能呼籲任何填補這個div元素的點擊()函數。我究竟做錯了什麼?
的代碼一路底部的塊是有問題的一個。
$(document).ready(function(){
function newGame(){
//Empty the game window of contents.
$('#previewWindow').empty();
//Add the following HTML to the game window.
$('#previewWindow').append("<div id='spriteBox' align='center'><img id='sprite1' src='images/sprites/172(noSelect).png' border='0'/><img id='sprite2' src='images/sprites/88(noSelect).png' border='0' /><img id='sprite3' src='images/sprites/196(noSelect).png' border='0' /><div id='info' align='center'>TEST</div></div>");
//Hover effects for Sid's character.
$('#sprite1').hover(function(){$(this).attr('src', 'images/sprites/172.png');$('#crumbling').get(0).play();},function(){$(this).attr('src','images/sprites/172(noSelect).png');}
);
//Hover effects for Grim's character.
$('#sprite2').hover(function(){$(this).attr('src', 'images/sprites/88.png');$('#crumbling').get(0).play();},function(){$(this).attr('src', 'images/sprites/88(noSelect).png');}
);
//Hover effects for Falas's character.
$('#sprite3').hover(function(){$(this).attr('src', 'images/sprites/196.png');$('#crumbling').get(0).play();},function(){$(this).attr('src','images/sprites/196(noSelect).png');}
);
};
//Execute the following code block if New Game is clicked.
$('#newGame').click(function(){
newGame();
});
//Execute the following code block if Sid is clicked.
$('#sprite1').click(function(){
alert('Hello');
});
});
聽起來像是你需要委派事件。不要忘記ID在文檔上下文中必須是唯一的。 https://learn.jquery.com/events/event-delegation/ –