JQuery 動態添加多個編輯器,ueditor等其他編輯器同樣適用

給別人隨手做的小demo,這邊只提供思路,代碼可再自行完善

<!DOCTYPE html>
<html lang="en">

<head>
  <title>demo</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <!-- 引用的外部文件 -->
  <script src="http://apps.bdimg.com/libs/ueditor/1.4.3.1/ueditor.config.js" type="text/javascript"></script>
  <script src="http://apps.bdimg.com/libs/ueditor/1.4.3.1/ueditor.all.min.js" type="text/javascript"></script>
</head>

<body>
  <div class="addBox">
    <script id="editor_0" type="text/plain" style="width:1024px;height:100px;"></script>
  </div>
  <div id="btns">
    <div>
      <button onclick="createEditor()">創建編輯器</button>
      <button onclick="deleteEditor()">刪除編輯器</button>
    </div>
  </div>

  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript">
    let arr = []; //存儲當前已經存在編輯器id的值,
    $(function() {
      // 如果後臺有數量則,直接遍歷渲染
      $('.addBox script').each(function() {
        arr.push($(this).attr('id').replace(/[^0-9]/ig, "")) //可以直接獲取最後一個編輯器的id,取出也行,這邊爲了後續操作方便,直接存儲id
      });

      arr.forEach(i => {
        initEditor(i)
      })
    });

    function createEditor() {
      if (arr.length != 0) { //如果已經有創建的編輯器,則直接添加
        // 創建時取最後一個編輯器id給他+1
        let newId = parseInt($('.addBox div[id^=editor_]:last').attr('id').replace(/[^0-9]/ig, "")) + 1;
        appendEditor(newId);
        initEditor(newId);
      } else {
        // 獲取到當前已經存在的編輯器id再繼續累加,直接使用時間戳當編輯器id也可以
        appendEditor(0);
        initEditor(0)
      }
    }
    // 刪除編輯器
    function deleteEditor(id) {
      // 刪除這邊傳個ID給下面銷燬就好了
      UE.getEditor(`editor${id}`).destroy();
    }

    // 初始化編輯器函數
    function initEditor(id) {
      UE.getEditor(`editor_${id}`);
    }
    // 創建編輯器
    function appendEditor(index) {
      arr.push(index)
      $('.addBox').append(`<script id="editor_${index}" type="text/plain" style="width:1024px;height:100px;"><\/script>`);
    }
  </script>
</body>

</html>

預覽效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章