如何动态加载javascript文件? [英] How do I load a javascript file dynamically?
本文介绍了如何动态加载javascript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码:
<script type="text/javascript">
function js() {
var getJs = document.getElementById("jogo");
if (JS == true) { //if button JS is pressed - it is correct?
< script type = "text/javascript"
src = "file1.js" >
} else < script type = "text/javascript"
src = "file2.js" >
</script>
}
</script>
它不起作用。我给了两个按钮,如果按下第一个按钮,则应加载 file1.js
。如果按下第二个,则应加载 file2.js
。
it doesn't work. I gave two buttons, if the first is pressed, file1.js
should be loaded. In case the second one is pressed, file2.js
should be loaded.
我该怎么办?
推荐答案
你不能以这种方式在Javascript中嵌入HTML。基本上,你想要的是嵌入一个脚本元素,在单击按钮时指向某个javascript文件。这可以通过将事件与DOM结合来实现:
You cannot embed HTML in Javascript in that way. Basically, what you want is to embed a script element, pointing to a certain javascript file when clicking a button. That can be done with combining events with DOM:
<script type="application/javascript">
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
</script>
<button onclick="loadJS('file1.js');">Load file1.js</button>
<button onclick="loadJS('file2.js');">Load file2.js</button>
这篇关于如何动态加载javascript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文