-1

第一次在 Stack 上提问,有人可以帮我弄清楚如何像开发控制台那样在视觉反馈中输出 eval,就像历史提要一样。

(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;	
};


})();
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>

我的意思(浏览器打印屏幕)

先感谢您。

4

1 回答 1

0

首先仔细阅读eval的作用,以确保它是你想要的。然后因为它试图评估一个表达式,所以try catch如果有异常,我会把它放在一个可以输出异常的地方。然后将结果或异常附加到文本区域。我还稍微调整了您的 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";

}	
};


})();
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>

于 2016-07-14T13:17:20.787 回答