[英]How do I run javascript code from a HTML input box?
I am currently trying to run JavaScript code from a HTML input box for my online code compiler project.我目前正在尝试从 HTML 输入框中为我的在线代码编译器项目运行 JavaScript 代码。
function runCode(){
let code = document.getElementById('code').value
console.log(code)
}
I was expecting it to actually run the code instead of just logging it as a string我期待它实际运行代码而不是仅仅将它记录为一个字符串
This is good if you're just playing around and having fun learning JavaScript and whatnot.如果您只是在玩耍并享受学习 JavaScript 之类的乐趣,这很好。 This is not something you just want to put out on the web if you aren't that experienced.
如果您没有那么多经验,这不是您只想在 web 上发布的内容。 If you do decide to put it on the web, make sure not to save anybody's code into a database.
如果您决定将其放在 web 上,请确保不要将任何人的代码保存到数据库中。 You don't want UserA to write code which may execute on UserB's computer.
您不希望 UserA 编写可以在 UserB 的计算机上执行的代码。 Given your experience level, I'd just say "don't do it".
鉴于您的经验水平,我只想说“不要这样做”。 Without further ado:
无需再费周折:
const userInput = 'console.log("Hello World");';
// method 1
eval(userInput);
// method 2
new Function(userInput)()
If you want to allow experimental javascript features and other new JS features, you will need to use babel standalone to transform the code first.如果你想允许实验性的 javascript 特性和其他新的 JS 特性,你需要先使用babel standalone来转换代码。 Something like this:
是这样的:
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
const userInput = 'console.log("Hello World");';
var output = Babel.transform(userInput, { presets: ["env"] }).code;
eval(output);
new Function(output)();
Use eval()
使用
eval()
run.onclick =() => { eval(editor.value) }
<textArea id="editor">console.log('test')</textArea> <button id="run">run</button>
Are you going to run the code on html input element?您要在 html 输入元素上运行代码吗? when?
什么时候? There should be at least an event.
至少应该有一个事件。 You can run the function when click input or focus in, change and so on.
单击输入或焦点、更改等时,您可以运行 function。 there are several solutions like onfocus, onkeypress, onkeyup, onchange, onclick
有几种解决方案,如 onfocus、onkeypress、onkeyup、onchange、onclick
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.