如何设置摩纳哥编辑并改变价值?

问题描述 投票:-1回答:1

我想使用monaco-editor来查看目录的不同文件。我想创建一个编辑器并动态更改内容。但它并不像我想要的那样工作。

function doSomething(val) {
  require.config({ paths: { 'vs': 'min/vs' }});
  require(['vs/editor/editor.main'], function() {
    monEditor = monaco.editor.create(document.getElementById("content"), {
      value: val,
      language: "plain",
      scrollBeyondLastLine: false,
      readOnly: true
    });
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<link type="text/css" href="min/vs/editor/editor.main.css" rel="stylesheet">

<body>
<!--- Modal start -->
<div id="content" style="height:100px; width: 100px;"> </div> <!-- Modal content -->
<!-- Modal end -->

<button onclick="doSomething('Input1')"> Change1 </button>
<button onclick="doSomething('Input2')"> Change2 </button>

<script src="min/vs/loader.js"></script>

</body>
</html>

这是我的代码。我第一次打开模态一切正常,但摩纳哥编辑器消失了。

当我尝试使用monEditor.setValue(val)时,出现错误,monEditor未定义。

当我尝试使用monEditor.setModel(model)时,会出现错误,表明找不到该节点。

有谁知道我做错了什么或我需要改变什么才能使它工作?我已经尝试了很多,但我没有让编辑器设置正确。不幸的是,这些示例也没有帮助我,因为它们包含不在存储库中的数据。

javascript monaco-editor visual-studio-monaco
1个回答
0
投票

JavaScript使用范围,这是执行的小上下文。在范围内声明的变量可以访问(“可见”)到当前范围的子范围,但不能访问任何外部范围。 (见the definition on the Mozilla Developer Networkthis comprehensive guide to JavaScript's scopes。)

您正在函数范围内定义monEditor变量,这就是您以后无法访问它的原因。您可以按如下方式重新定义您的功能:

let monEditor;

function doSomething (val) {
    require.config ({ paths: { 'vs': 'min/vs' }});
    require (['vs/editor/editor.main'], function () {
        monEditor = monaco.editor.create (document.getElementById ("content"), {
          value: val,
          language: "plain",
          scrollBeyondLastLine: false,
          readOnly: true
        });
    });
}

这里monEditor在全球范围内定义,使其可用于所有功能。试图重新声明它会引发错误,因为monEditor是用let声明的。

© www.soinside.com 2019 - 2024. All rights reserved.