更新时获取 Codemirror 文本框值

Get Codemirror textbox value on update

所以我正在尝试使用 Codemirror 从网页获取输入,我希望它在文本输入发生变化时更新 Javascript 中的值。目前我有这个工作,但用户必须按下按钮才能将输入发送到 JS 文件。

<!DOCTYPE html>
<html>
    <head>
        <title>CodeMirror</title>
    <script src="codemirror/lib/codemirror.js"></script>
    <link href="codemirror/lib/codemirror.css" rel="stylesheet"></link>
    <script src="codemirror/mode/xml/xml.js"></script>
    <script src="codemirror/addon/edit/closetag.js"></script>
    <link href="codemirror/theme/dracula.css" rel="stylesheet"></link>
    </head>
    <body>
        <textarea id="editor"><p>A paragraph</p></textarea>

    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
        mode: "xml",
        theme: "dracula",
        lineNumbers: true,
        autoCloseTags: true
      });

        function showCode() {
             var text = editor.getValue()
             console.log(text);
        }
    </script>

        <input id="clickMe" type="button" value="clickme" onclick="showCode();" />
    </body>
</html>

我怎样才能基本上使按钮自动化,以便每当 Codemirror 文本区域的值发生变化时,JS 脚本就会运行。

使用 <textarea>onchange 属性:

<textarea id="editor" onchange="showCode();"><p>A paragraph</p></textarea>

'change' 事件会在发生变化时通知您。

const editor = CodeMirror.fromTextArea(document.getElementById('editor'), {});
editor.on('change', (editor) => {
  const text = editor.doc.getValue()
  console.log(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.41.0/codemirror.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.41.0/codemirror.min.css" rel="stylesheet"></link>
<textarea id="editor"><p>A paragraph</p></textarea>