[英]Unable to attach event listeners to element rendered in froala rich text editor
[英]Recursively replaced element with editor (and back) breaks event listeners
背景:我的網站上有一些值可以通過JavaScript和Ajax編輯。 Ajax工作正常,我可以編輯值,但在保存值后,我無法再次編輯它而無需重新加載頁面。
我將問題簡化為:原始元素被HTML表單替換。 提交表單時,表單本身將由新版本的display元素替換,但事件偵聽器已損壞。
我把一些示例JS代碼( JSfiddle )放在一起,它不能像我期望的那樣工作。
var text = $('<em/>').text('click me!');
text.click(function() {
var button = $('<input type="button" value="Click me, too" />');
button.click(function() {
$('#container').html(text);
});
$('#container').html(button);
})
$('#container').html(text);
會發生什么:
click
ed文本替換為窗體(為簡單起見保存文本元素) click
顯示的文本 click
文本再次工作,如步驟2(現在不起作用) 為什么再次使用text
對象時click
事件會丟失?
使其工作而不是重寫整個結構的一個選項是使用綁定事件克隆元素:
text.click(function() {
...
button.click(function() {
$('#container').html(text.clone(true));
});
...
})
$('#container').html(text.clone(true));
演示: http : //jsfiddle.net/J8Sa7/2/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.