从一个文本框执行代码并在另一个文本框中显示输出 [英] Execution of code from one textbox and display output in another textbox

查看:185
本文介绍了从一个文本框执行代码并在另一个文本框中显示输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个文本框,在第一个文本框中我必须编写我的JAVASCRIPT代码,当我点击按钮时,想要在我的第二个文本框中输出。我使用了以下方法执行代码,但整个页面正在重新加载并显示输出。





Having two textbox, in first text box i have to write my JAVASCRIPT code and when i click button, want my output in my second text box. I had used the following method its executing the code but the entire page is getting reload and output is getting displayed.


<script>
function doIt() {
    var headID = document.getElementsByTagName("head")[0];
    var newScript = document.createElement("script");
    newScript.type = "text/javascript";
    newScript.innerHTML = document.getElementById("textarea").value;
    headID.appendChild(newScript);
}

</script>

推荐答案

获取一个textarea的文本:

Take the text of one textarea:
var code = document.getElementById("textarea").value;



结果将是


The result will be

var result = eval(code);



以你想要的方式呈现这个结果。



你可能想做什么还有更多,但最重要的下一步是处理用户输入的代码中的所有异常,方法是使用围绕 eval 调用的try-catch块并显示异常信息。



请参阅:

https://developer.mozilla.org/en-US/docs/Web / JavaScript / Reference / Global_Objects / eval [ ^ ],

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch [ ^ ],

https://developer.mozilla.org/en-US/docs / Web / JavaScript / Reference / Global_Objects / Error [ ^ ]。



请查看我的计算器,以及更多(所有代码,包括脚本,在一个HTML文件中):< a href =http://sakryukov.org/freeware/calculator> http://sakryukov.org/freeware/calculator [ ^ ]。



-SA


Present this result the way you want.

You may want to do a lot more, but the most important next step would be handling all exceptions in the code the user enters, by using try-catch block around the eval call and showing exception information.

Please see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval[^],
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch[^],
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error[^].

Please see my calculator doing this, and a lot more (all code, including the script, is in one HTML file): http://sakryukov.org/freeware/calculator[^].

—SA


这篇关于从一个文本框执行代码并在另一个文本框中显示输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆