如何在codemirror文本编辑器中使用onchange、onmouseup事件

How to use onchange, onmouseup event in codemirror text editor

我正在使用我的文本编辑器作为代码镜像。通常当我尝试在 textarea 中使用 dom 之类的 onmouseup, onchange, oninput 事件时它可以工作,但是在集成 codemirror 之后,它不起作用。请告诉我在我的文本编辑器中调用这些事件的正确方法。

没有 codemirror,它可以工作。

<textarea id="editor" rows="30" cols="100" onchange="myFunction()" onmouseup="second();"></textarea>        
<div id="demo"></div>
<div id="second"></div> 
<script>
  function myFunction() {
       document.getElementById('demo').innerHTML="The onchange function..";}    
  function second() {
       document.getElementById('second').innerHTML="The mouseup function..";}
</script>       

在集成codemirror 文本编辑器时,它不起作用。这是一个代码:

<textarea id="editor" onchange="myFunction()" onmouseup="second();"></textarea>
<div id="demo"></div>
<div id="second"></div> 
<script>
    var editor = CodeMirror.fromTextArea
    (document.getElementById('editor'),{
            mode:"text/x-java",
            lineNumbers:true,
            autoCloseTags:true,
            tabSize:5       
    });
    editor.setSize("1000", "450");              
    </script>       
    <script>
    function myFunction() {
          document.getElementById('demo').innerHTML="The onchange function..";}         
    function second() {
         document.getElementById('second').innerHTML="The mouseup function..";}

    </script>

因为这些事件实际上并没有发生在 textarea 上,因为它是隐藏的,相反,您需要将事件绑定到 .CodeMirror 元素,如下所示:

$(document).on('mouseup', '.CodeMirror', function() {
    // do something...
});
$(document).on('change', '.CodeMirror', function() {
    // do something...
});

此外,我使用 keyup 而不是 change 事件,因为您必须单击 .CodeMirror 才能使更改功能 运行...