Javascript 如何获取Codemirror textarea的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10285301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:40:52  来源:igfitidea点击:

How to get the value of Codemirror textarea

javascriptcodemirror

提问by Nitin Kabra

I am using Codemirror's plugin for textarea but I am not able to retrieve the value of textarea.

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

Code:

代码:

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


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

It is showing the error:

它显示错误:

editor.getCode() is not a function.

回答by Eric Leschinski

Try using getValue()instead of getCode().

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

Pass in an optional argument into getValue(separator) to specify the string to be used to separate lines (the default is \n).

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

回答by Siddhartha Mukherjee

This works fine for me.

这对我来说很好用。

editor.getValue()

回答by Satya Pendem

use your_editor_instace.getValue();

使用 your_editor_instace.getValue();

It will work fine because there is no function named with the name as getCode() in codemirror.

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

for setting value use your_editor_instance.setValue();

设置值使用 your_editor_instance.setValue();

回答by pme

Version: 5

版本:5

According to the Documentation, you need now to do it like:

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

doc.getValue(?separator: string) → string

doc.getValue(?separator: string) → string

So in this example:

所以在这个例子中:

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

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

回答by Mohammad Reza

I know you are using textareabut I hope this code will be useful for others! I have this problem but with articletag, and this is my solution to getting all codes with jquery:

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

res_array = []
$.each($('article.code-draft span[role="presentation"]'), function(){
    res_array.push($(this).text())
});
console.log(res_array.join('\n'))