如何运行放置在文本框中的 Javascript 代码(在 HTML5 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5012604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run Javascript codes that are put in a textbox (in HTML5)
提问by Mark
I have a textbox on my html page, I'd like to run the javascript code that people put it the textbox. How can I do that?
我的 html 页面上有一个文本框,我想运行人们将其放入文本框的 javascript 代码。我怎样才能做到这一点?
回答by ayush
回答by Spidy
You can create a new script dynamically like found here
您可以像在此处找到的那样动态创建新脚本
Here's a quick example you can copy and paste into an html file and see it work. You'll notice that once called, the page reloads and stalls out. This could be solved by using ajax and a seperate page the executes the code and returns a value or string or whatever it is your code should return.
这是一个快速示例,您可以将其复制并粘贴到 html 文件中并查看它的工作情况。您会注意到,一旦被调用,页面会重新加载并停止。这可以通过使用 ajax 和一个单独的页面来解决,该页面执行代码并返回一个值或字符串或您的代码应该返回的任何内容。
<html>
<head>
</head>
<body>
<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 name="textarea" id="textarea">
</textarea>
<input type="button" value="Do It" onclick="doIt();" />
</body>
<html>
回答by dextervip
You could also create a JavaScript function to get the content using jQuery and execute the code you wanted but you must set an id to the textbox
您还可以创建一个 JavaScript 函数来使用 jQuery 获取内容并执行您想要的代码,但您必须为文本框设置一个 id
<script>
$("#run").click(function () {
var element = $("input#textbox").val();
//code to execute
}
</script>
<input type="textbox" value="Type something" id="textbox"></input>
<button id="run">Run Code</button>

