[英]When I edit the code in a TextArea using CodeMirror how to reflect this into another textarea with js or jQuery
App:我的頁面中有一個textarea元素。 它使用CodeMirror進行轉換,因為我需要縮進並突出顯示html代碼。 Pic在鏈接中:[textarea using codemirror]
http://uploadingit.com/file/gxftd2cps9wm7zhp/cm.png
以下是使用codemirror的textarea代碼:
</textarea>
<button type="submit">Post</button>
</form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: { name: "xml", htmlMode: true },
lineNumbers: true,
tabMode: "indent",
matchBrackets: true,
path: 'js/',
searchMode: 'inline',
onCursorActivity: function () {
editor.setLineClass(hlLine, null);
hlLine = editor.setLineClass(editor.getCursor().line, "activeline");
}
});
var hlLine = editor.setLineClass(0, "activeline");
</script>
怎么做?:當我點擊Post按鈕時,所有代碼都應該傳輸到另一個textarea。 我需要這與javascript或jQuery,但努力如何做到這一點。 任何幫助?
對於真實世界的應用程序,此textarea中的代碼(來自上圖)應該影響Html Designer API。 即,Html設計器中的任何更改都應該反映在此textarea(使用codemirror以提高可讀性)和相反的情況。 當我在textarea中編輯時,更改應該反映在HtmlDesigner中,但在此模擬案例中 - >在第二個textarea中。
示例:與Visual Studio .Net WebPage代碼編輯器一樣,具有Designer + Source模式。 現在很清楚了嗎?
我問如何使用javascript或jquery實現上述機制。 非常感謝!
將onChange選項傳遞給CodeMirror,如下所示:
onChange: function (cm) {
mySecondTextArea.value = cm.getValue();
}
編輯注意:從CodeMirror 2.0版開始,您不再傳遞onChange
選項來注冊更改處理程序,而是調用instance.on("change", function(cm, change) { ... })
。 http://codemirror.net/doc/manual.html#event_change
最新發布的版本(v 3.15)適用於此解決方案:
// on and off handler like in jQuery
CodemirrorInstance.on('change',function(cMirror){
// get value right from instance
yourTextarea.value = cMirror.getValue();
});
這工作工作CodeMirror 5.22.0:
CodeMirror.fromTextArea(document.getElementById('grammar'), {
lineNumbers: true,
mode: 'pegjs',
}).on('change', editor => {
console.log(editor.getValue());
});
代碼鏡像中的onChange處理不是這樣的:
onChange: function(cm) { mySecondTextArea.value = cm.getValue(); }
你必須使用:
$.fn.buildCodeMirror = function(){
var cmOption {...};
var cm = CodeMirror($("MyDomObjectSelector")[0],cmOption);
cm.on("change",$.fn.cmChange);
}
$.fn.cmChange = function(cm,cmChangeObject){
alert("code mirror content has changed");
}
那么你想要從一個TextArea(順便提一下作為input
控件)復制文本到另一個文本區域?
//Set the button to call a Javascript function when it is clicked
<button type="submit" onclick="copyText();">Post</button>
<script type="text/javascript">
function copyText() {
//Get the text in the first input
var text = document.getElementById("firstTextArea").getValue();
//Can't use .value here as it returns the starting value of the editor
//Set the text in the second input to what we copied from the first
document.getElementById("secondTextArea").value = text;
}
</script>
你可以用這個......
var editor_js = CodeMirror.fromTextArea(document.getElementById("js"), {
mode: 'text/javascript',
theme: 'icecoder',
styleActiveLine: true,
lineNumbers: true,
lineWrapping: true,
});
並使用editor_js.getValue()
獲取數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.