当前位置:软件学堂 > 资讯首页 > 网络编程 > 编程其他 > 通过JS代码在网页中动态添加Script脚本

通过JS代码在网页中动态添加Script脚本

2012/10/14 10:56:06作者:佚名来源:网络

移动端

【实例名称】

通过JS代码在网页中动态添加Script脚本

【实例描述】

Script脚本可以在页面中静态地设置好,也可以使用“src”属性调用页面外部的脚本文件,本例JS代码我们来学习一个方法,可以在页面运行过程中,动态添加Script脚本。

【实例代码】

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>标题页</title>
<script>
    o=document.createElement("script");         //动态创建script元素
    o.text="alert('test!')";                    //输出语句。。是脚本中的代码
    document.documentElement.childNodes[0].appendChild(o);//将脚本添加到页面中
</script>
</head>
<body>
</body>
</html>

【难点剖析】

本例JS代码使用“createElement”方法,创建了一个“script”元素,并设置元素的内容为“atert('test!')”,最后使用“appendChild”方法,将此元素添加到窗体中。

【源码下载】

本实例JS代码下载

标签: 网页  JS代码