2016-11-16 44 views
0

嘗試使用輸入按鈕和javascript將文件加載到CKEditor 4 textarea中。這些文件包含簡單的HTML代碼,並具有擴展名.inc和.txt使用Javascript將文件加載到CKEditor textarea中

我有什麼作品,但只使用瀏覽器後退/前進按鈕(學生髮現錯誤)。使用來自本地驅動器的輸入加載文件,textarea變爲空白,但加載的文件僅在使用瀏覽器後退/前進按鈕後出現?

下面是我們所使用的HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
    <script src="https://cdn.ckeditor.com/4.5.11/standard/ckeditor.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
    </head> 
<body> 

     <textarea name="editor1" id="editor1" rows="10" cols="80"> 
      Placeholder text... 
     </textarea> 
     <script> 
      CKEDITOR.replace('editor1'); 
     </script> 

     <input name="file" type="file" id="files" class="form-control" value=""> 

     <script type="text/javascript"> 
       function readTextFile(file, callback, encoding) { 
      var reader = new FileReader(); 
      reader.addEventListener('load', function (e) { 
       callback(this.result); 
      }); 
      if (encoding) reader.readAsText(file, encoding); 
      else reader.readAsText(file); 
     } 

     function fileChosen(input, output) { 
      if (input.files && input.files[0]) { 
       readTextFile(
        input.files[0], 
        function (str) { 
         output.value = str; 
        } 
       ); 
      } 
     } 

     $('#files').on('change', function() { 
     var result = $("#files").text(); 
     //added this below testing 
     fileChosen(this, document.getElementById('editor1')); 
     CKEDITOR.instances['editor1'].setData(result); 
     }); 
     </script> 

</body> 
</html> 

而且放在JSFiddle

W3schools

FYI:瀏覽器後退/前進的奧祕並不上述兩個網站只上工作,當我使用本地或服務器時。

經過3天試圖在課堂上解決這個問題,我來這裏要求輸入。我們花了幾個小時嘗試不同的方法在這裏和許多網站。

安全性不是輸入文件限制的問題,只能在教室中用於培訓目的/示例。

有人嗎?

+0

我可能是錯的,但你不應該載入jQuery的** **之前的CKEditor的javascript文件?我相信Bootstrap也有一個未加載的JavaScript文件。 –

+0

@AlejandroIván嘗試過,仍然以相同的結果結束。但認爲你是正確的。 – Woody

+0

另一個注意事項:真的不需要引導CSS,只是用它來加載文件的樣式。 – Woody

回答

1

好的,我設法讓它工作。 爲了替換文本,您需要在CKEDITOR實例上調用setData(str);方法,而不是通過DOM元素。您還需要告訴編輯更新(「重繪」)其內容。

所以:

fileChosen

function fileChosen(input, output) { 
     if (input.files && input.files[0]) { 
      readTextFile(
       input.files[0], 
       function (str) { 
        output.setData(str); // We use the setData() method 
        output.updateElement(); // Then we tell the CKEditor instance to update itself 
       } 
      ); 
     } 
    } 

文件輸入變化

$('#files').on('change', function() { 
    var result = $("#files").text(); 
    fileChosen(this, CKEDITOR.instances.editor1); // We pass the CKEDITOR instance, not the DOM element 
}); 

我也做了類似CKEDITOR javascript文件之前進口的jQuery的變化。

檢查結果in this fiddle

+0

絕對的輝煌!完美的作品。我們在課堂上花了幾個小時(並學到了很多),努力工作,並在幾分鐘內完成工作。謝謝並接受了您的答案。 – Woody

相關問題