2014-04-10 48 views
0

下面的代碼通過AJAX將數據添加到所述容器#section:.on()處理程序不能處理用.html()創建的元素,爲什麼?

$(".btnGetImages").click(function(event){ 
    event.preventDefault(); 

    // get id of article 
    var id = $(this).attr('data-id'); 

    // get images via ajax 
    $.ajax({ 
     url: "includes/get_images.php", 
     type: "get", 
     data: {article:id}, 
     success: function(data) { 
      // insert data into container 
      $("#section").html(data); 
     }, 
     error:function() { 
      $("#section").html('show error msg here...'); 
     } 
    }); 
}); 

裏面的容器#section有與類.thumb,我想點擊元素。出於某種原因,點擊不會觸發,即使我正確添加.on事件。爲什麼?

$(".thumb").on("click", function(event) { 
    alert('yo, im a thumb...'); 

    event.preventDefault(); 
}); 
+0

事件代表團..... – lifetimes

+0

@null:我讀過關於代表團,但它說代表()已被.on()方法取代... – Marco

+0

所以你讀過關於如何使用'on ()'?顯然不是,因爲那不是你寫的。 – Barmar

回答

1

因爲它們是動態創建的,所以您需要使用event delegation。因爲你需要重新申請任何事件處理程序的任何動態生成的代碼

$("#section").on("click", ".thumb", function(event) { 
    event.preventDefault(); 
    alert('yo, im a thumb...'); 
}); 
1

:使用'#section'的選擇,因爲它比使用document更有效。

function foo() { 
    alert('foo'); 
} 

$('body').html('<p>something in here</p>'); 
$('body p').on('click', foo); 

最好的方法是預先定義一個函數,然後將它分配爲事件處理程序。當jQuery被加載時,它會運行HTML代碼並將任何已定義的事件處理程序分配給存在的任何HTML代碼。如果添加到文檔中,則事件偵聽器不存在,因此您需要重新應用它們。

0

您需要添加成功函數內部的事件偵聽器($(」拇指‘)。在(’點擊.....),否則Ajax請求回來之前,它可能加載。

+0

使用事件委派的重點是讓您不需要這樣做。 – Barmar

相關問題