How can I set the value of a CodeMirror editor using Javascript?

放肆的年华 提交于 2019-11-30 13:08:43

问题


I try to set id4 in the following code:

<div id="id1">
    <div id="id2">
        <div id="id3">
            <textarea id="id4"></textarea>
        </div>
    </div>
</div>

By using this code:

document.getElementById('id4').value = "...";

And this:

document.getElementById('id3').getElementsByTagName('textarea')[0].value = "...";

But nothing works.

UPDATED:

The textarea is replaced by CodeMirror editor. How do I set value to it?

Thanks a lot for the help!


回答1:


The way to do this has changed slightly since the release of 3.0. It's now something like this:

var textArea = document.getElementById('myScript');
var editor = CodeMirror.fromTextArea(textArea);
editor.getDoc().setValue('var msg = "Hi";');



回答2:


I like examples. Try this:

CodeMirror.fromTextArea(document.getElementById(id), {
        lineNumbers: true
    }).setValue("your code here");



回答3:


CodeMirror ~4.6.0 you can do this, assuming you have a codemirror object:

var currentValue = myCodeMirrorObject.cm.getValue();
var str = 'some new value';
myCodeMirrorObject.cm.setValue(str);



回答4:


The code you have should work. The most likely explanation for it failing is that the elements do not exist at the time you run it. If so the solutions are to either:

  • Move the JS so it appears after the elements have been created (e.g. to just before </body>)
  • Delay execution of the JS until the elements have been created (e.g. by moving it to a function that you assign as the onload event handler)



回答5:


This has worked for my (pretty old) version of CodeMirror:

var editor=CodeMirror.fromTextArea('textarea_id');

editor.setCode('your string');


来源:https://stackoverflow.com/questions/8378678/how-can-i-set-the-value-of-a-codemirror-editor-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!