我想使用monaco编辑器来查看一个目录下的不同文件。我想创建一个编辑器,并动态更改内容。但这并不是我想要的方式。
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>
这是我的代码。第一次打开模式时,一切都很好,但之后monaco编辑器就消失了。
当我尝试使用monEditor.setValue(val)
时,出现未定义monEditor的错误。
当我尝试使用monEditor.setModel(model)
时,出现一个错误,指出找不到该节点。
有没有人知道我做错了什么,或者我需要改变什么才能让它正常工作?我已经尝试了很多,但是我不能正确设置编辑器。不幸的是,这些示例对我也没有帮助,因为它们包含的数据不在存储库中。
发布于 2019-02-20 17:31:10
JavaScript使用作用域,作用域是执行的小上下文。在一个作用域中声明的变量可以被当前作用域的子作用域访问(“可见”),但不能被任何外部作用域访问。(请参见the definition on the Mozilla Developer Network和this 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
声明的,所以尝试重新声明它会抛出错误。
https://stackoverflow.com/questions/54756901
复制相似问题