CodeMirror - 单击按钮时更改编辑器值

时间:2016-07-13 13:06:45

标签: javascript jquery textarea codemirror

我尝试更改代码镜像编辑器中的值,但它无法正常工作。

function myFunction() {
    getFi();//get the new code
    editor.setValue(fi);
    editor.refresh();
}

我也尝试更改文本区域值,但它不起作用。

function myFunction() {
    getFi();//get the new code
    document.getElementById('code').value = fi;
    editor.refresh(); 
}

编辑:部分代码,这里是编辑器的初始化和应加载代码的函数

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src='http://codemirror.net/lib/codemirror.js'></script>
<script src='http://codemirror.net/mode/xml/xml.js'></script>
<script src='http://codemirror.net/mode/javascript/javascript.js'></script>
<script src='http://codemirror.net/mode/css/css.js'></script>
<script src='http://codemirror.net/mode/htmlmixed/htmlmixed.js'></script>
</head>
<body>
<textarea id="code" name="code" ></textarea>
<button type="button" id="execute" onclick="myFunction()">Load Code</button>
<script>
    var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
        mode: 'text/javascript',
        tabMode: 'indent',
        lineNumbers: true,
        lineWrapping: true,
        autoCloseTags: true,
        indentWithTabs: true
    });

    function myFunction() {
        getFi();//get the new code
        editor.setValue(fi);
        editor.refresh();
    }

    function getFi(){
        /*get new code from a file*/
    }
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以尝试get a reference to the CodeMirror instance

    function myFunction() {
        var editor = $('.CodeMirror')[0].CodeMirror;
        editor.setValue(fi);
        editor.refresh();
    }