<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<textarea id="js" style="width: 500px;height: 300px;"></textarea>
<button onclick="initJS(document.getElementById('js').value)">执行</button>
<script>
function initJS(scriptText){
//获取head的标签
var head= document.getElementsByTagName('head')[0];
//创建script标签
var script= document.createElement('script');
//属性赋值
script.type= 'text/javascript';
//下面为必要操作 否则将不能使用script标签中的内容
script.onload = script.onreadystatechange = function() {
if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete" ) {
script.onload = script.onreadystatechange = null;
} };
//添加src属性值
script.innerText=scriptText;
head.appendChild(script);
}
</script>
</body>
</html>
如下图:
主要就是这个js方法:
function initJS(scriptText){ //获取head的标签 var head= document.getElementsByTagName('head')[0]; //创建script标签 var script= document.createElement('script'); //属性赋值 script.type= 'text/javascript'; //下面为必要操作 否则将不能使用script标签中的内容 script.onload = script.onreadystatechange = function() { if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete" ) { script.onload = script.onreadystatechange = null; } }; //添加src属性值 script.innerText=scriptText; head.appendChild(script); }