2012-04-23 226 views
44

我正在使用Codemirror的textarea插件,但我无法检索textarea的值。如何获取Codemirror textarea的值

代码:

var editor = CodeMirror.fromTextArea(document.getElementById("code"), { 
    lineNumbers: true, 
    matchBrackets: true, 
    mode: "text/x-csrc" 
    }); 


function showCode() 
{ 
    var text = editor.mirror.getCode(); 
    alert(text); 
} 

它显示错误:

editor.getCode() is not a function. 
+1

'console.dir(editor.morror)'和'console.dir(editor)'在chrome中显示的是什么? – sissonb 2012-04-23 17:56:49

回答

59

尝试使用getValue()代替getCode()

将可选参数传入getValue(分隔符)以指定用于分隔行的字符串(默认值为\n)。

+1

有没有一种方法可以在不调用getValue()的情况下获得对文本的引用?如果你在编辑器中有很多文本,这个函数真的很慢,它会锁定UI线程。 – Gubatron 2013-09-06 02:47:37

+0

cm.getValue()和cm.doc.getValue()是否有区别? – 425nesp 2014-08-14 23:16:15

22

这对我很好。

editor.getValue() 
0

use your_editor_instace.getValue();

它会正常工作,因为在codemirror中没有名称为getCode()的函数。

设置值使用your_editor_instance.setValue();