如何获取Codemirror textarea的值

问题描述 投票:54回答:5

我正在使用Codemirror的textarea插件,但我无法检索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.
javascript codemirror
5个回答
74
投票

尝试使用getValue()而不是getCode()

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


26
投票

这对我来说很好。

editor.getValue()

2
投票

使用your_editor_instace.getValue();

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

设置值使用your_editor_instance.setValue();


0
投票

版本:5

根据Documentation,您现在需要这样做:

doc.getValue(?separator: string) → string

所以在这个例子中:

editor.getDoc().getValue("\n")


0
投票

我知道你正在使用textarea,但我希望这段代码对其他人有用!我有这个问题,但使用article标记,这是我用jquery获取所有代码的解决方案:

res_array = []
$.each($('article.code-draft span[role="presentation"]'), function(){
    res_array.push($(this).text())
});
console.log(res_array.join('\n'))
© www.soinside.com 2019 - 2024. All rights reserved.