[英]Adding rich text editors dynamically in HTML/JavaScript (subsequent instances produce text areas instead)
我有一個 flask web 應用程序,我正在嘗試在 HTML 模板中動態添加富文本編輯器。 但是,只有第一個字段是富文本編輯器,其他字段顯示為文本區域。
這是第一個富文本編輯器框,帶有用於添加新文本的按鈕和用於刪除文本的按鈕 (HTML):
<div class='f_elements'>
<div id='inputFormFormalElements'>
<textarea name="f_element[]" id="f_element[]" class="ckeditor"></textarea>
<button id="removeFormalElement" type="button" class="btn btn-danger">Remove</button>
</div>
<div id="newFormalElement"></div>
<button id="addFormalElement" type='button' class="btn btn-info">Add a slot</button>
</div>
編輯:這是動態添加新字段的腳本:
$(document).on('click', '#addFormalElement', function(){
$("#newFormalElement").append('<div id="inputFormFormalElements"><textarea name="f_element[]" id="f_element[]" class="ckeditor"></textarea><button id="removeFormalElement" type="button" class="btn btn-danger">Remove</button>');
CKEDITOR.replaceAll('ckeditor');
});
$(document).on("click", "#removeFormalElement", function(){
$(this).closest('#inputFormFormalElements').remove();
});
編輯:現在的問題是,當我單擊按鈕(添加新字段)時,第二個編輯器正常添加,但是當我嘗試添加第三個字段和更多后續字段時,前兩個字段突然合並(他們之間沒有中斷)。
正如您在屏幕截圖中看到的,在我向原始字段添加了兩個字段之后,我得到了 2 個合並字段 + break + 另外 2 個合並字段 + break + 和另一個字段(總共 5 個字段)。 預期的行為將總共獲得 3 個字段,並在它們之間進行分隔。
如果有人能指出我做錯了什么,我將不勝感激。
注意:動態添加的元素id相同是可以的。 然后,我將在與 Python 中的列表相同的鍵下收集所有輸入。
我似乎找到了解決辦法!
顯然,沖突是由於新添加的文本編輯器框具有相同的 id 而引起的,而 ckeditor 不允許這樣做。 所以,我唯一改變的是我現在正在動態更新添加的 ckeditor 框的 id。
現在一切正常!
// add formal elements
let i = 1;
$(document).on('click', '#addFormalElement', function(){
$("#newFormalElement").append('<div id="inputFormFormalElements"><textarea name="f_element[]" id="f_element[]' + i + '" class="ckeditor"></textarea><button id="removeFormalElement" type="button" class="btn btn-danger">Remove</button>');
CKEDITOR.replace('f_element[]' + i);
i++
});
// remove formal elements
$(document).on("click", "#removeFormalElement", function(){
$(this).closest('#inputFormFormalElements').remove();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.