如何动态加载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则应加载。


我怎样才能做到这一点?


HUWWW
浏览 319回答 3
3回答

繁星点点滴滴

您不能以这种方式将HTML嵌入Javascript。基本上,您想要的是嵌入一个脚本元素,单击按钮时指向某个javascript文件。这可以通过将事件与DOM结合来完成:<script type="application/javascript">function loadJS(file) {&nbsp; &nbsp; // DOM: Create the script element&nbsp; &nbsp; var jsElm = document.createElement("script");&nbsp; &nbsp; // set the type attribute&nbsp; &nbsp; jsElm.type = "application/javascript";&nbsp; &nbsp; // make the script element load file&nbsp; &nbsp; jsElm.src = file;&nbsp; &nbsp; // finally insert the element to the body element in order to load the script&nbsp; &nbsp; document.body.appendChild(jsElm);}</script><button onclick="loadJS('file1.js');">Load file1.js</button><button onclick="loadJS('file2.js');">Load file2.js</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript