2013-11-03 38 views
0

所以我使用jQuery來創建它,所以當您點擊運行按鈕時,它將從文本區域獲取文本並將其放入名爲繪圖的分隔線中。Javascript正在使用代碼鏡像的HTML更新div

我會把代碼和鏈接在下面進行測試,然後描述問題。

代碼:

<link rel=stylesheet href="codemirror/lib/codemirror.css"> 
<link rel=stylesheet href="codemirror/doc/docs.css"> 
<script src="codemirror/lib/codemirror.js"></script> 
<script src="codemirror/mode/xml/xml.js"></script> 
<script src="codemirror/mode/javascript/javascript.js"></script> 
<script src="codemirror/mode/css/css.js"></script> 
<script src="codemirror/mode/htmlmixed/htmlmixed.js"></script> 
<script src="codemirror/addon/edit/matchbrackets.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<style> 
    .CodeMirror { height: auto; border: 1px solid #ddd; } 
    .CodeMirror-scroll { max-height: 200px; } 
    .CodeMirror pre { padding-left: 7px; line-height: 1.25; } 
    #drawing { left:550px; top:10px; border: 1px solid #555555; width:500px; height: 400px; } 
</style> 
    <form style="position: relative; margin-top: .5em;"> 
    <textarea id=demotext name="textarea"> 
<html> 
    <head> 
     <title>Learning HTML</title> 
    </head> 
    <body> 
     <p>I'm learning HTML! This is my first line of code!</p> 
    </body> 
</html> 
    </textarea> 
<input type="button" id="run" value="Run" /> 
<center> 
<br /> 
<div id="drawing"> 
</div> 
</center> 

</form> 
<script> 
$(document).ready(function(){ 
    $("#run").click(function(){ 
     $('#drawing').html($("#demotext").val()); 
    }); 
}); 
</script> 
    <script> 
    var editor = CodeMirror.fromTextArea(document.getElementById("demotext"), { 
     lineNumbers: true, 
     mode: "text/html", 
     matchBrackets: true 
    }); 
    </script> 

鏈接:http://codeeplus.net/test.php

所以,基本上當你點擊運行它不會與你輸入時,它與已投入實際中的文本更新文本更新網頁的HTML。例如,如果我編輯<p><h1>,它將運行它作爲<p>而不是<h1>,因爲放入的核心文本是<p>

不知道如何描述它,改變textarea中的文本,然後查看頁面源,如果你不明白我的意思。

如果您需要更多信息,請讓我知道!

+1

爲什麼您的表單標籤在您的html標籤上方?你textarea標籤格式不正確。 *編輯*沒關係,它只是全部被打亂。 – keyboardSmasher

+0

我不能在id爲「demotext」的textarea中輸入事件,因爲它甚至不可見。它的'display'設置爲'none'。 – WannaCSharp

+0

@keyboardSmasher我不認爲你明白這是怎麼回事,那標籤和下面基本上textarea中的所有東西都是文本.. – user2812028

回答

2

嘗試

$(document).ready(function(){ 
    $("#run").click(function(){ 
     $('#drawing').html(editor.doc.getValue()); 
    }); 
}); 

而且這不是一個好主意,開始把多餘的htmlbody標籤和這樣在該專區。考慮使用iframe來代替。

+0

我該如何將它設置爲iFrame?我以前就是這樣,但它不起作用。順便這個工作!謝謝!我會接受你的回答:) – user2812028

+0

嘗試http://stackoverflow.com/questions/8814411/getting-the-html-content-of-an-iframe-using-jquery,但設置html而不是獲取它。 –

+0

嗯......這個怎麼了? 。$( '#圖紙')的內容()HTML(editor.doc.getValue()); – user2812028

0

它不起作用的原因是CodeMirror不會不斷更新textarea。由於您使用了fromTextArea(),因此您可以撥打editor.save()來更新textarea的值。
(見http://codemirror.net/doc/manual.html#fromTextArea

保羅與editor.doc.getValue()解決方案是更有效的方式來做到這一點。