2012-11-19 90 views
2

我想使用jQuery來選擇已添加到HTML5內容可編輯div的項目。它現在不工作,因爲當頁面加載時該項目不存在。 如何告訴jQuery div已被更新?如何告訴jQuery內容可編輯div已更新

請參見本的jsfiddle測試代碼:http://jsfiddle.net/kthornbloom/sjHYQ/

$(document).ready(function() { 

<!-- This wont work on an image dragged into the div after page load --> 
$('#editor img').click(function(){ 
    $(this).fadeOut(); 
}); 

});​ 

我已經看到了這個其他問題,但沒有一個似乎適用於內容編輯股利。

回答

3

嘗試:

$('#editor').on('click', 'img', function() { 
    $(this).fadeOut(); 
});​ 

jsFiddle example

因爲你基本上結合動態元素,你需要使用.on()委派#editor元素上的點擊事件,因爲有編輯器專區內沒有圖像加載頁面時。

+1

謝謝,這就是我一直在尋找的。也欣賞.on()的快速解釋 – kthornbloom

0

您需要使用.on() JQuery function到事件附加到動態創建

下面是一個例子元素(我用身體作爲主要的集裝箱,但你需要更具體):

$("#editor").on({ 
    click: function (event) {  
     console.log('test') 
     $(this).fadeOut(); 
    } 
    }, 
    "img" 
); 

這裏小提琴http://jsfiddle.net/sjHYQ/2/