通过选择菜单即时更改代码镜像模式

Change Codemirror mode on the fly through a select menu

本文关键字:代码 镜像 模式 选择 菜单      更新时间:2023-09-26

我正在尝试使用以下方法即时更改代码镜像模式,但不幸的是它不起作用,欢迎您的帮助

我有一个选择菜单,例如:

<select name="idLanguage" id="select" onChange="selectMode()">
<option value="1">Python</option>
<option value="10">JavaScript</option>
<option value="33">Asterisk dialplan</option>
<option value="34">Clojure</option>
<option value="35">Common Lisp</option>
<option value="36">D</option>
<option value="37">ECL</option>
<option value="38">Go</option>
<option value="39">Haskell</option>
<option value="40">HTML</option>
<option value="41">Jinja2</option>
<option value="42">LiveScript</option>
<option value="43">mIRC</option>
</select>

然后我使用这个javascript方法:

var modeInput = document.getElementById("select");
function selectMode() {
  var myindex  = modeInput.selectedIndex;
  var modefly = modeInput.options[myindex].text.toLowerCase();
  alert(modefly); // This is giving me the exact mode on the screen
  editor.setOption("mode", modefly);// no change in the mode
  CodeMirror.autoLoadMode(editor, modefly);//no change in the mode
  //editor.refresh();
   }

尽管alert()给出了正确的答案,但模式并未改变

知道吗?

谢谢

更新:

我正在加载标头中的所有模式(python,javascript等..)我更改了代码镜像资产的结构,我有一个名为 assets 的目录,其中包含一个文件夹js包含所有 javascript,包括代码镜像模式,所以我认为这不再有效

CodeMirror.modeURL = "../mode/%N/%N.js";

我应该如何解决它?使用我现在拥有的文件夹配置,即使是懒惰模式示例也不起作用

更新 我只记得我的模式转换器永远不会工作,除非我提供镜像期望的 MIME 类型代码,而不是模式名称。 即text/x-markdown传递它而不是markdown

我在我的网站上使用最新版本的代码镜像 http://pste.me.

通过选择菜单,可以使用以下命令更改模式:

$('#mode').change(function(){
   editor.setOption("mode", $(this).val() );
});

其中editor是对CodeMirror.fromTextArea对象的引用。

我不是代码镜像专家,但我相信不再使用添加模式/自动加载方法。我对它自动加载所需文件没有任何问题,但是您始终可以在设置模式之前动态构建新的脚本标签并将其附加到文档head

这就是我们用于编辑器主题的方法:

// Append the theme styles
var link = document.createElement('link');
link.onload = function(){
    pste.editor.setOption("theme", theme);
};
link.rel = "stylesheet";
link.media = "all";
link.href = INTERFACE_URL+"/codemirror/theme/"+theme+".css";
document.getElementsByTagName('head')[0].appendChild(link);

这个解决方案对我有用,希望你觉得这很有用。

在 html 文件中加载这些脚本

<script
  type="text/javascript"
  src="/node_modules/codemirror/lib/codemirror.js"
></script>
<script
  src="/node_modules/codemirror/addon/mode/loadmode.js"
  defer
></script>

并加入您的脚本.js

CodeMirror.modeURL = "/node_modules/codemirror/mode/%N/%N.js";
let editor = CodeMirror.fromTextArea(document.querySelector("textarea"), {
  lineNumbers: true,
  value: "",
  matchBrackets: true,
  autoCloseBrackets: true,
});
var modeInput = document.getElementById("select");
function selectMode() {
  var myindex  = modeInput.selectedIndex;
  var modefly = modeInput.options[myindex].text.toLowerCase();
  alert(modefly); 
  //Make sure to use valid MIME type according to the selected input
  editor.setOption("mode", modefly);
  CodeMirror.autoLoadMode(editor, modefly);
  //editor.refresh();
}