【问题标题】:How to get the value of Codemirror textarea如何获取 Codemirror textarea 的值
【发布时间】:2012-05-04 08:17:23
【问题描述】:

我正在使用 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.

【问题讨论】:

  • console.dir(editor.morror)console.dir(editor) 在 chrome 中显示什么?

标签: javascript codemirror


【解决方案1】:

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

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

【讨论】:

  • 有没有办法在不调用 getValue() 的情况下获得对文本的引用?如果你在编辑器中有很多文本,这个功能真的很慢,它会锁定 UI 线程。
  • cm.getValue()cm.doc.getValue()有区别吗?
【解决方案2】:

这对我来说很好。

editor.getValue()

【讨论】:

    【解决方案3】:

    使用 your_editor_instance.getValue();

    它可以正常工作,因为 CodeMirror 中没有名为 getCode() 的函数。

    设置值使用your_editor_instance.setValue();

    【讨论】:

      【解决方案4】:

      版本:5

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

      doc.getValue(?separator: string) → string

      所以在这个例子中:

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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

          这适用于您尝试捕获 CodeMirror 文本区域中返回的文本的 C++ Selenium 实例:

          var myText = this.WebDriver.ExecuteJavaScript<string>("return $editor[0].getValue()");
          

          其中[0]是表单中代码镜像文本区域的索引。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-12-04
            • 2012-05-17
            • 1970-01-01
            • 1970-01-01
            • 2011-12-15
            • 2011-03-23
            相关资源
            最近更新 更多