当我使用CodeMirror在TextArea中编辑代码时,如何使用js或jQuery将其反映到另一个textarea中

A.M*_*ano 20 javascript asp.net jquery visual-studio-2010 codemirror

App:我的页面中有一个textarea元素.它使用CodeMirror进行转换,因为我需要缩进并突出显示html代码.Pic在链接中:[textarea using codemirror]

http://uploadingit.com/file/gxftd2cps9wm7zhp/cm.png

以下是使用codemirror的textarea代码:

</textarea>
    <button type="submit">Post</button>       
</form>
 <script>

   var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
     mode: { name: "xml", htmlMode: true },
     lineNumbers: true,
     tabMode: "indent",
     matchBrackets: true,
     path: 'js/', 
     searchMode: 'inline',
     onCursorActivity: function () {
       editor.setLineClass(hlLine, null);
       hlLine = editor.setLineClass(editor.getCursor().line, "activeline");
     }
   });

   var hlLine = editor.setLineClass(0, "activeline");
  </script>
Run Code Online (Sandbox Code Playgroud)

怎么做?:当我点击Post按钮时,所有代码都应该传输到另一个textarea.我需要这与javascript或jQuery,但努力如何做到这一点.任何帮助?

对于真实世界的应用程序,此textarea中的代码(来自上图)应该影响Html Designer API.即,Html设计器中的任何更改都应该反映在此textarea(使用codemirror以提高可读性)和相反的情况.当我在textarea中编辑时,更改应该反映在HtmlDesigner中,但在此模拟案例中 - >在第二个textarea中.

示例:与Visual Studio .Net WebPage代码编辑器一样,具有Designer + Source模式.现在很清楚了吗?

我问如何使用javascript或jquery实现上述机制.非常感谢!

Mar*_*ijn 32

将onChange选项传递给CodeMirror,如下所示:

onChange: function (cm) {
   mySecondTextArea.value = cm.getValue();
}
Run Code Online (Sandbox Code Playgroud)

编辑注意:自CodeMirror 2.0版以来,您不再传递onChange选项来注册更改处理程序,而是调用instance.on("change", function(cm, change) { ... }).http://codemirror.net/doc/manual.html#event_change

  • 自此评论以来API是否已更改?使用`{onChange:function(cm){alert("foo"); `似乎对我不起作用 (2认同)

Ник*_*нев 21

最新发布的版本(v 3.15)适用于此解决方案:

// on and off handler like in jQuery
CodemirrorInstance.on('change',function(cMirror){
  // get value right from instance
  yourTextarea.value = cMirror.getValue();
});
Run Code Online (Sandbox Code Playgroud)


mpe*_*pen 9

这工作工作CodeMirror 5.22.0:

CodeMirror.fromTextArea(document.getElementById('grammar'), {
    lineNumbers: true,
    mode: 'pegjs',
}).on('change', editor => {
    console.log(editor.getValue());
});
Run Code Online (Sandbox Code Playgroud)


Bri*_*ett 1

那么您想将文本从一个 TextArea(input顺便说一下,它呈现为控件)复制到另一个 TextArea 吗?

//Set the button to call a Javascript function when it is clicked
<button type="submit" onclick="copyText();">Post</button>

<script type="text/javascript">
    function copyText() {
        //Get the text in the first input
        var text = document.getElementById("firstTextArea").getValue(); 
        //Can't use .value here as it returns the starting value of the editor

        //Set the text in the second input to what we copied from the first
        document.getElementById("secondTextArea").value = text;
    }
</script>
Run Code Online (Sandbox Code Playgroud)