javascript 使用 CKEditor 动态添加文本区域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12781203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:05:58  来源:igfitidea点击:

Dynamically add textareas with CKEditor

javascriptckeditordynamically-generated

提问by Francisco Presencia

I am trying to create a dynamical form where you can add new 'chapters' clicking to a button up to 10 of them. This would be 'easy', but I also want the text fields to be implementing CKEditor, and I cannot make it work. I got it adding the chapters smoothly, I can only edit the LAST instance of them. Besides, if I edit the last one and click on 'add new chapter', the last one gets deleted. I based my attempt in this thread.

我正在尝试创建一个动态表单,您可以在其中添加新的“章节”点击按钮,最多 10 个。这将是“容易”,但我也希望文本字段实现 CKEditor,但我无法使其工作。我顺利添加了章节,我只能编辑它们的最后一个实例。此外,如果我编辑最后一个并单击“添加新章节”,最后一个会被删除。我的尝试基于此线程

Javascript code I got so far:

到目前为止我得到的 Javascript 代码:

num_chapter = 1;
var editor = new Array();

function createEditor()
  {
  if (num_chapter <= 10)
    {
    var num=num_chapter+1;
    document.getElementById('editor').innerHTML += "<br><br><h3 style='display:inline'>Chapter " + num + ": </h3><input style='display:inline' type='text' name='titlechapter_" + num + "' placeholder='Title for chapter " + num + "'><br><br>";    

    // Create a new editor inside the <div id="editor">, setting its value to html
    var config = {};
    editor[num_chapter] = CKEDITOR.appendTo( 'editor' , config, '' );
    }
  else
    {
    document.getElementById('chapters').innerHTML += "<br />Maximum is 10 chapters.";
    }
  num_chapter += 1;
  }

HTML code:

HTML代码:

<h3 style='display:inline'>Chapter 1: </h3> <input style='display:inline' type="text" name="titlechapter_1" placeholder="Title chapter 1"><br><br>
<textarea class="ckeditor" onChange="editing('Chapter 1');" name="chapter_1"></textarea>
  <div id="editor">
  </div><br>
  <input type="button" onclick="createEditor(); editing('Chapter 1');" value=" Add chapter ">

As you can see, I attempted to put the editors objects into an array, but it didn't work out. I don't know much Javascript (not to say almost nothing), so any help will be appreciated!

如您所见,我尝试将编辑器对象放入一个数组中,但没有成功。我不太了解 Javascript(不是说几乎没有),所以任何帮助将不胜感激!

采纳答案by Francisco Presencia

I finally solved it, after 3 or 4 hours in total. It was easier than I thought, but not so elegant. This can be achieved through php and javascript to make it 'slightly' more elegant, but just plain old html and Javascript will also do the trick if you have few text fields.

我终于解决了它,总共花了 3 到 4 个小时。这比我想象的要容易,但并不那么优雅。这可以通过 php 和 javascript 来实现,使其“稍微”更优雅,但是如果文本字段很少,那么简单的旧 html 和 Javascript 也可以解决问题。

First, the HTML/PHP:

首先,HTML/PHP:

<h3 style='display:inline'>Chapter 1: </h3> 
  <input style='display:inline' type="text" name="titlechapter_1" placeholder="Title chapter 1"><br><br>
  <textarea class="ckeditor" onChange="editing('Chapter 1');" name="chapter_1"></textarea>
  <?php for ($i=2; $i<=10; $i++)
    echo "<div id='div_editor_".$i."' style='display:none;'><textarea id='editor_".$i."' name='editor".$i."'></textarea></div>"; ?>
  <br><br>
  <input type="button" onclick="createEditor();" value=" Add chapter ">
<br><br>

Realize that it creates all the div, but since there's nothing in them, they don't appear. Then, the Javascript:

意识到它创建了所有的 div,但由于它们中没有任何内容,因此它们不会出现。然后,Javascript:

num_chapter = 2;
var editor = new Array();

function createEditor()
  {
  if (num_chapter <= 10)
    {
    toggle_visibility('div_editor_' + num_chapter );

    document.getElementById('div_editor_' + num_chapter).insertAdjacentHTML( "afterbegin", "<br><br><h3 style='display:inline'>Chapter " + num_chapter + ": </h3><input style='display:inline' type='text' name='titlechapter_" + num_chapter + "' placeholder='Title for chapter " + num_chapter + "'><br><br>");

    // Create a new editor inside the <div id="editor">, setting its value to html
    CKEDITOR.replace( 'editor_' + num_chapter );

    num_chapter += 1;
    }
  else
    {
    alert("Sorry, maximum is 10 chapters.");
    }
  }

This code will generate 10 chapters properly working with CKeditor. If the 11th is attempted to be created, a warning in a popup is shown. it's important that this line for ($i=1; $i<10; $i++), this num_chapter < 10and this num_chapter == 10have all the same value (10 in my case).

此代码将生成 10 章与 CKeditor 一起正常工作。如果尝试创建第 11 个,则会在弹出窗口中显示警告。重要的是这一行for ($i=1; $i<10; $i++),这num_chapter < 10和这num_chapter == 10都具有相同的值(在我的例子中是 10)。

回答by rob

After some trial and error, I finally found the solution to this problem.

经过一番反复试验,我终于找到了这个问题的解决方案。

This is to answer searches that may land here as I did, looking for 'how to dynamically create ckeditor instances'.

这是为了回答可能像我一样在这里登陆的搜索,寻找“如何动态创建 ckeditor 实例”。

The trick is to include the adapter library included in CKEDITOR in your html script in addition to the ckeditor.js library

诀窍是除了 ckeditor.js 库之外,还要在 html 脚本中包含 CKEDITOR 中包含的适配器库

ckeditor/adapters/jquery.js

And initialize these elements in your javascript

并在您的 javascript 中初始化这些元素

 var elem = $(this).find('.your_selector')
 elem.ckeditor()

(Making sure .your_selector is the class of a textarea which will be converted to a ckeditor instance)

(确保 .your_selector 是将被转换为 ckeditor 实例的 textarea 的类)

Hope this helps people who may still be finding this thread.

希望这对可能仍在寻找此线程的人有所帮助。

回答by Chandra Shekhar

Appending CKEditor 4Dynamically to the Element creating multiple instances of the CKEditor

CKEditor 4动态附加到创建 CKEditor 的多个实例的 Element

Javascript

Javascript

function createNewEditor(targetElement) {
  var element = document.createElement("textarea");
  $(element)
    .addClass(".ckeditor")
    .appendTo(targetElement);
  return CKEDITOR.replace(element);
}

$(document).ready(function() {
  $(".ckeditor").each(function(_, ckeditor) {
    CKEDITOR.replace(ckeditor);
  });

  $(".chapter-video").each(function(_, chapterVideo) {
    var chapterVideoInput = $(chapterVideo).find(".file-input");
    var chapterFileUploadName = $(chapterVideo).find(".upload-file-name");
    $(chapterVideoInput).on("change", function(e) {
      var filesLength = e.target.files.length;
      if (filesLength) {
        $(chapterFileUploadName)
          .find("span")
          .text(e.target.files[0].name);
      }
    });
  });
  $(".add-chapter-para").each(function(_, addParaBtn) {
    var addTo = $(addParaBtn).data("add-to");
    $(addParaBtn).on("click", function() {
      createNewEditor(addTo);
    });
  });
});

HTML

HTML

<div class="container">
  <form action="#">
    <div class="" id="main-container">
      <div class="editor">
        <textarea class="ckeditor" name="chapterContent[]"></textarea>
      </div>
    </div>
    <div class="my-2">
      <button class="btn btn-primary">Submit</button>
    </div>
  </form>
</div>

<hr />
<button
  class="btn btn-danger add-chapter-para"
  data-add-to="#main-container"
  type="button"
>
  Add Paragraph
</button>

Button Element is having a data-attributeto which element we want to append the ckeditor.

按钮元素有一个data-attribute我们想要将 ckeditor 附加到哪个元素。

Working Codepen Link

工作 Codepen 链接