FileReader and CodeMirror Load File Complication

六眼飞鱼酱① 提交于 2019-11-29 07:54:33

You're simply misusing CodeMirror; when the file content is loaded into the reader, instead of assigning a value to the textarea element, e.g.:

reader.onload = function(e) {
    document.getElementById('code').value = e.target.result;
}

… use the CodeMirror API and insert content via the editor instance setValue() method, like so:

reader.onload = function(e) {
    editor.setValue(e.target.result);
}

See the CodeMirror docs for doc.setValue(content: string), and here's the updated, working demo illustrating this.

Here is sample example.

<script src="codemirror/lib/codemirror.js"></script>
<link rel="stylesheet" href="codemirror/lib/codemirror.css"/>
<script src="codemirror/mode/clike/clike1.js"></script>
<script src="codemirror/mode/javascript/javascript.js"></script>

<div id="editor"> </div>
<div>
    <input type="file" onchange="localLoad(this.files);" />
</div>

<script>
   var myCodeMirror = CodeMirror(
   document.getElementById('editor'), {
      lineNumbers: true
   });

   function localLoad(files) {
       if (files.length == 1) {
            document.title = escape(files[0].name);
            var reader = new FileReader();
            reader.onload = function(e) {
              myCodeMirror.setValue(e.target.result);
            };
            reader.readAsText(files[0]);
         }
    }
</script>

The above one is done for div. If you wanted for textarea, change it like:

<textarea id="editor" name="field1"></textarea>

 <script>
 var myCodeMirror = CodeMirror.fromTextArea
  document.getElementById('editor'),{
  lineNumbers: true
   });
   myCodeMirror.setSize(null, 600);
 </script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!