(转载)向页面某处动态添加js的方法

1、不能用innerHTML向div中写入"<script></script>"。
解决办法:
(1)在添加一个其他的html标记:obj.innerHTML="<br><script>"+scriptStr+"</script>";
(2)使用如下脚本:

var obj=document.getElementById("test");
var str="alert('xx');var a=100;document.write(a);document.write('aaaa')";
var oScript=document.createElement("script");
oScript.text
=str;
obj.appendChild(oScript);

2、无法执行脚本中的document.write脚本,或者说执行时把页面内容清空了。
原因:document.write只有在加载时执行才不会清空页面内容,其他时间执行则会清空页面内容。

解决办法:既然document.write的目的就是在指定的div中写入内容,把脚本中的document.write替换为innerHTML不久ok了吗?

经过多次测试终于ok了。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" lang="zh-CN">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<body>
<div id="test">

</div>
<input type="button" onclick="test()" />
<script type="text/javascript">
function addScript(id,str){
window.execScript((str
+";").replace(/<\/?script[^\)]*>/ig,"").replace(/document.write\((.*?)\)[\s;]/ig,function(){
return ("document.getElementById('"+id+"').innerText+="+arguments[1]+";");
}));
}

window.onload
=function(){
var id="test";
var str="alert('xx');\nvar a=100;document.write('(xxx)');document.write('aaaa')\n";
addScript(id,str)
};
</script>
</body>

来源:http://www.cnitblog.com/yemoo/archive/2007/07/19/30237.html

原文地址:https://www.cnblogs.com/backuper/p/1619458.html