【问题标题】:CodeMirror using jQuery .keyup on editor textareaCodeMirror 在编辑器文本区域上使用 jQuery .keyup
【发布时间】:2014-06-28 09:11:16
【问题描述】:

我想在 keyup 上获取 Codemirror 编辑器的值,但它不起作用。 这里是the fiddle

var mixedMode = {
        name: "htmlmixed",
        scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i,
                       mode: null},
                      {matches: /(text|application)\/(x-)?vb(a|script)/i,
                       mode: "vbscript"}]
      };
      var editor = CodeMirror.fromTextArea(document.getElementById("HTML"), {mode: mixedMode,lineNumbers: true  });

$(document).ready(function(){
  $("#HTML").keyup(function(){
    html = editor.getValue();
    alert(html);
    });
}); 

【问题讨论】:

  • ReferenceError: CodeMirror is not defined
  • @undefined 我已将 CodeMirror 链接到我的网页,编辑器工作正常
  • 你的jsfiddle中抛出了错误。无法重现指定问题的演示根本没有帮助。
  • @undefined 抱歉,codeMirror 编辑器无法正常工作,因为无法在线链接 jsfiddle 中的 codeMirror 库,假设它已链接并正常工作,请您帮忙解决 keyup 问题。
  • 不用担心。实际上jsfiddle 允许在其左侧面板中添加外部 CSS/JavaScript 文件,您可以附加所需的文件。这是一个托管 CodeMirror 文件的 CDN cdnjs.com/libraries/codemirror

标签: javascript jquery textarea codemirror onkeyup


【解决方案1】:

CodeMirror 隐藏了textarea 元素,为了监听编辑器实例的事件,您可以使用on 方法:

$(document).ready(function () {
    editor.on('change', function () {
        html = editor.getValue();
        alert(html);
    });
});

您可以在 CodeMirror 的手册中找到支持的事件列表。

http://codemirror.net/doc/manual.html#events

【讨论】:

    【解决方案2】:
    editor.on("keyup", function(cm, event) {
        //only show hits for alpha characters
        if(!editor.state.completionActive && (event.keyCode > 65 && event.keyCode < 92)) {
            if(timeout) clearTimeout(timeout);
            var timeout = setTimeout(function() {
                CodeMirror.showHint(cm, CodeMirror.hint.clike, {completeSingle: false});
            }, 150);
        }
    });
    

    用您使用的任何提示模式替换“CodeMirror.hint.cilke”:)

    【讨论】:

    • 我发现keyup 函数的性能优于change 函数。
    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    相关资源
    最近更新 更多