2016-07-14 121 views
-1

第一次詢問Stack時,有人可以幫我弄清楚我怎樣才能像開發控制檯那樣在視覺反饋中輸出eval,就像是歷史記錄feed。製作歷史記錄如console.log

(function init() { 
 
var btn = document.getElementById("btn").onclick = function(){ 
 
      var iostore = document.getElementById("io"); 
 
      var history = document.getElementById("history"); 
 
      var result = eval(iostore.value); 
 
      console.log(result); 
 
      iostore.value = result; \t 
 
}; 
 

 

 
})();
body, html{width:100%;height:100%;margin: 0px auto;background-color:#EEE;} 
 
#io{background-color:aqua;width:auto;height:auto;border:0;outline:none;font-size:1.5em;} 
 
button{border:0;border-radius: 5px;background-color:#999;font-size:1.7em;}#history{resize: none;background-color:#EEE;border:0;outline:none;cursor:default;color:black;opacity:0.7;}#creation{background-color:aqua;width:auto;height:auto;border:0;outline:none;font-size:1.5em;}
<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
<meta charset="UTF-8"> 
 
<title>Document</title> 
 
</head> 
 
<body> 
 
<div class="interfacecontainer"> 
 
<input type="text" id="io"> 
 
<button id="btn">run</button><br> 
 
<textarea id="history"></textarea> 
 
<div id="creation"></div> 
 
</div> 
 
</body> 
 
</html>

What i mean (browser print-screen)

預先感謝您。

+0

只需更新textarea的內部價值。 'history.textContent + =結果'或'history.innerHTML + =結果'。 eval也是邪惡的,除非你真的需要它,否則永遠不要使用它。這是完全不需要的情況。 'iostore.value'應該會自動給你輸入內的文本,不需要評估它。 – Shilly

回答

0

首先閱讀eval確切地確定它的用途。然後,因爲它試圖評估一個表達式,我將它放在一個try catch中,如果有異常,您可以輸出異常。然後在textarea附加結果或異常。我也調整了一下textarea的大小,這樣你可以看到更多的結果。

(function init() { 
 
var btn = document.getElementById("btn").onclick = function(){ 
 
      var iostore = document.getElementById("io"); 
 
      var history = document.getElementById("history"); 
 
try { 
 
var result =eval(iostore.value); 
 
history.value += result+"\n"; 
 
} catch (e) { 
 
    iostore.value=e.message; 
 
history.value += e.message+"\n"; 
 

 
} \t 
 
}; 
 

 

 
})();
body, html{width:100%;height:100%;margin: 0px auto;background-color:#EEE;} 
 
#io{background-color:aqua;width:auto;height:auto;border:0;outline:none;font-size:1.5em;} 
 
button{border:0;border-radius: 5px;background-color:#999;font-size:1.7em;}#history{resize: none;background-color:#EEE;border:0;outline:none;cursor:default;color:black;opacity:0.7;height:50px}#creation{background-color:aqua;width:auto;height:auto;border:0;outline:none;font-size:1.5em;}
<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
<meta charset="UTF-8"> 
 
<title>Document</title> 
 
</head> 
 
<body> 
 
<div class="interfacecontainer"> 
 
<input type="text" id="io"> 
 
<button id="btn">run</button><br> 
 
<textarea id="history"></textarea> 
 
<div id="creation"></div> 
 
</div> 
 
</body> 
 
</html>