本教學示範如何解決 jQuery 的 Click Event 不能應用在新加的元素上的問題。在很多情況下,我們都會使用 JQuery 更改網頁的內容。而一些原先捆綁的事件有可能不能應用在新加的元素上。
jQuery 版本 1.3 至 1.7
正常來說,我們會使用「.click()」建立事件。
$('#block1').click(function(e) {
// Action
$('#add').click(function(e) {
var newBlock1 = $('<div id=block1 style=width: 100px; height: 100px; background-color: red; cursor: pointer;></div>');
var newBlock2 = $('<div id=block2 style=width: 100px; height: 100px; background-color: green; cursor: pointer;></div>');
$('body').append(newBlock1);
$('body').append(newBlock2);
$(this).remove();
$('#block1').click(function(e) {
alert(TEST RESULT 1);
$('#block2').live(click, function(e) {
alert(TEST RESULT 2);
$('#add').click(function(e) {
var newBlock1 = $('<div id=block1 style=width: 100px; height: 100px; background-color: red; cursor: pointer;></div>');
var newBlock2 = $('<div id=block2 style=width: 100px; height: 100px; background-color: green; cursor: pointer;></div>');
$('body').append(newBlock1);
$('body').append(newBlock2);
$(this).remove();
$('#block1').click(function(e) {
alert(TEST RESULT 1);
$(document).on(click, '#block2', function(e) {
alert(TEST RESULT 2);
紅色的方塊沒有效果,綠色方塊出現效果。