有时,我们需要在js文件中引用其它js文件。方法如下:
html代码:
程序代码
<html>
<body>
<input type="button" value="ok" onclick="javascript:b()">
</body>
<script language="JAVASCRIPT" src='b.js'></script>
</html>
b.js代码:
程序代码
new_element=document.createElement("script");
new_element.setAttribute("type","text/javascript");
new_element.setAttribute("src","a.js");
document.body.appendChild(new_element);
function b() {
a();
}
a.js代码:
程序代码
function a() {
alert("a");
}
html代码:
程序代码
<html>
<body>
<input type="button" value="ok" onclick="javascript:b()">
</body>
<script language="JAVASCRIPT" src='b.js'></script>
</html>
b.js代码:
程序代码
new_element=document.createElement("script");
new_element.setAttribute("type","text/javascript");
new_element.setAttribute("src","a.js");
document.body.appendChild(new_element);
function b() {
a();
}
a.js代码:
程序代码
function a() {
alert("a");
}
本文介绍了一种在JavaScript文件中动态加载另一个JS文件的方法。通过创建新的script元素并设置其src属性为待加载的JS文件路径来实现。示例展示了如何在一个按钮点击事件中触发加载过程,并调用加载文件中的函数。

被折叠的 条评论
为什么被折叠?



