2012-03-09 156 views
1

我正在使用javascript在我的頁面下動態創建腳本標記。到目前爲止,我能夠創建它,能夠設置它的類型和src。現在我的問題是,是否有任何方法,而不是定義src到一個不同的頁面,我可以分配其內容在同一頁面上?讓我寫我的代碼,使其更有意義:在腳本標記下編寫內容

var script = document.createElement("script"); 
script.type = "text/javascript"; 
script.src = 'custom.js'; 

現在有什麼辦法我可以做這樣的事情給它分配的內容以及:

script.content = 'document.write("stackoverflow")'; 
script.html = 'document.write("stackoverflow")'; 

我不知道是否他們是否存在,但只是猜測我是否可以做這樣的事情。

+2

你能解釋一下你正在努力實現的,而不是你是怎麼想的,你可能會實現嗎?編寫動態腳本到目前爲止沒有任何意義。你也不想在頁面加載後使用document.write,因爲它會擦除你所在的頁面 – mplungjan 2012-03-09 06:48:50

+0

@mplungjan我知道它會擦掉整個頁面,我正在測試一些東西,因此解釋整個故事並沒有任何意義。其他工作正常,我只是尋找一種方式,我可以在腳本標記下以動態方式分配內容 – 2012-03-09 06:53:58

+0

分配給'script.text'應該做的訣竅 - 當然你分配的必須是一個有效的程序。 – RobG 2012-03-09 07:01:04

回答

11

你可以這樣做:

var script_tag = document.createElement('script'); 
script_tag.type = 'text/javascript'; 
script_tag.text = 'alert("hello world")'; 
document.body.appendChild(script_tag); 

在實踐中,是否設置type屬性或不很可能無關緊要,但它提供了一個溫暖的內發光。

+0

工作正常,當我用純JavaScript的但沒有與jquery工作...說$沒有定義,雖然我已經包含jQuery的副本:-( – 2012-03-09 07:13:14

+1

如果你插入的腳本,需要jQuery,你需要確保它是第一次加載。 – RobG 2012-03-09 13:46:11

2

使用'scripts.text'可以讀取或寫入腳本。它是腳本數據對象模型(DOM)的一部分。由於某種原因,它與其他HTML標籤不同。例如:'myScript.innerHTML'往往不起作用,但是'scripts.namedItem(「myScript」).text'會。

<p>Change scripts.text <a href="https://www.w3schools.com/jsref/prop_script_text.asp">https://www.w3schools.com/jsref/prop_script_text.asp</a> 
 
</p> 
 

 
<p>Script Object <a href="https://www.w3schools.com/jsref/dom_obj_script.asp">https://www.w3schools.com/jsref/dom_obj_script.asp</a> 
 
</p> 
 

 
<canvas id="Canvas1" style="border: 5px solid cyan"></canvas> 
 
<p id="Para1">...</p> 
 
<button onclick="ChangeScript()">Change Script</button> 
 
<button onclick="DrawIt()">Drawit</button> 
 
<button onclick="para1.innerHTML=script1.text;">Show Script</button> 
 

 

 
<script id="Script1"></script> 
 

 
<script> 
 
    function ChangeScript() { 
 
    script1.text = "function DrawIt(){canvas1.fillRect(1,2,30,40)}" 
 
    } 
 

 
    //Note: changing the script text more than once may not work. 
 

 
    canvas1 = document.getElementById("Canvas1").getContext("2d"); 
 
    script1 = document.scripts.namedItem("Script1"); 
 
    para1 = document.getElementById("Para1") 
 
</script> 
 

 

 

 
<a href="http://www.w3schools.com/code/tryit.asp?filename=FCR1ZI3MBN77">Try it Yourself, Change scripts.text</a>

+0

解釋你的答案 – 2017-02-15 05:22:07

相關問題