我有以下代码:
<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则应加载。
file1.js
file2.js
我怎样才能做到这一点?
您不能以这种方式将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>