我有以下代码: <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则应加载。我怎样才能做到这一点?
3 回答
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
您不能以这种方式将HTML嵌入Javascript。基本上,您想要的是嵌入一个脚本元素,单击按钮时指向某个javascript文件。这可以通过将事件与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>
添加回答
举报
0/150
提交
取消