簡體   English   中英

如何設置摩納哥編輯器並更改值?

[英]How to set up monaco-editor and change value?

我想使用 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 使用范圍,它是執行的小上下文。 在作用域內聲明的變量可以被當前作用域的子作用域訪問(“可見”),但不能被任何外部作用域訪問。 (請參閱Mozilla 開發人員網絡上的定義JavaScript 范圍的綜合指南。)

您正在函數作用域內定義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聲明的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM