2016-08-03 95 views
0

我試圖將代碼添加到腳本,但它只是不工作如何我添加代碼到<script></script>

var script= document.createElement('script'); 
    script.type= 'text/javascript'; 
    script.textContent = var Module = { 
     TOTAL_MEMORY: 536870912, 
     errorhandler: null, 
     compatibilitycheck: null, 
     dataUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.data", 
     codeUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.js", 
     memUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.mem", 
    }; 
    script.async = true; 
    document.body.appendChild(script); 

如何添加變成這個樣子? enter image description here

回答

1

這樣;轉義雙引號(用"包圍內部內容),反之亦然。另一種方法是使用一個數組來使你的代碼可讀性,使用.join()

var script= document.createElement('script'); 
 
    script.type= 'text/javascript'; 
 
    script.textContent = 'var Module = { TOTAL_MEMORY: 536870912, errorhandler: null, compatibilitycheck: null, dataUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.data", codeUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.js", memUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.mem", };'; 
 
    script.async = true; 
 
    document.body.appendChild(script);

使用陣列加入他們的行列:

var script= document.createElement('script'); 
 
    
 
    scriptContent = ['var Module = {', 
 
     'TOTAL_MEMORY: 536870912,', 
 
     'errorhandler: null,', 
 
     'compatibilitycheck: null,', 
 
     'dataUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.data",', 
 
     'codeUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.js",', 
 
     'memUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.mem",', 
 
    '};', 
 
    'console.log(Module)'].join(""); 
 

 
    script.type= 'text/javascript'; 
 
    script.textContent = scriptContent; 
 
    script.async = true; 
 
    document.body.appendChild(script);

0

只寫你這樣的代碼:

<script> 
    // your javascript code 
</script> 

或創建另一個JavaScript文件,例如。

<script src="location/of/main.js"></script> 
0

現代瀏覽器允許

script.textContent = `var Module = { 
    TOTAL_MEMORY: 536870912, 
    errorhandler: null, 
    compatibilitycheck: null, 
    dataUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.data", 
    codeUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.js", 
    memUrl: "Release/Arctopia_Path_Monopoly_v1.1.1GL.mem", 
};`; 
: 「main.js」,然後右鍵身體年底前在HTML加載
相關問題