2012-03-21 48 views
1

我剛開始定義和實現外部的javaScript庫,我對規則有點困惑。以下是三個文件「top.js」,「bottom.js」和「ref.html」的內容。文件「bottom.js」包含對「top.js」的引用,文件「ref.html」包含對「bottom.js」的引用。在「ref.html」中,我試圖通過直接調用函數並通過「bottom.js」中的另一個函數調用函數來訪問「top.js」中的函數,但這兩種方法似乎都不起作用。任何建議,將不勝感激。從另一個引用一個java腳本庫

topTest.js:

function top_test() { 
alert('Test from top'); 
} 

bottom.js

function bottom() { 
alert("bottom"); 
top_test(); 
} 

loadScript('topTest.js'); // Call function (function declarations are evaluated 
        // before the rest of the code, so this works) 

function loadScript(file_name) { 
var newScript = document.createElement('script'); 
var scripts = document.getElementsByTagName('script'); 

// Reference to the latest (this) <script> tag in the document 
scripts = scripts[scripts.length-1]; 

// Set target 
newScript.src = file_name; 

// Clean-up code: 
newScript.onload = newScript.onerror = function() { 
    this.parentNode.removeChild(this); 
}; 

// Insert script in the document, to load it. 
scripts.parentNode.insertBefore(newScript, scripts); 

}

ref.html

<html> 
<head> 
<script type="text/javascript" src="bottom.js"></script> 
</head> 
<body> 
test 
<script type="text/javascript"> 
bottom(); 
top(); 
</script> 
</body> 
</html> 

回答

1

<script>標籤必須從去除文件。

這些標籤是只有需要在HTML文檔中,用於標記內容的一部分爲腳本。 JavaScript文件的全部內容都是JavaScript,因此添加<script>標籤沒有任何意義,因此無效。

要在<head>在腳本中包括JavaScript,您可以使用圖書館,或者一個下面的方法:

創建使用document.createElement一個<script>標籤,並在文檔中插入腳本。您bottom.js例如:

function bottom() { 
    alert("bottom"); 
    top(); 
} 
loadScript('top.js'); // Call function (function declarations are evaluated 
         // before the rest of the code, so this works) 

function loadScript(file_name) { 
    if (document.readyState === 'loading') { // Chrome 
     document.write('<script src="' + file_name.replace(/"/g, '&quot;') + '"></script>'); 
     return; 
    } 
    var newScript = document.createElement('script'); 
    var scripts = document.getElementsByTagName('script'); 

    // Reference to the latest (this) <script> tag in the document 
    scripts = scripts[scripts.length-1]; 

    // Set target 
    newScript.src = file_name; 

    // Clean-up code: 
    newScript.onload = newScript.onerror = function() { 
     this.parentNode.removeChild(this); 
    }; 

    // Insert script in the document, to load it. 
    scripts.parentNode.insertBefore(newScript, scripts); 
} 
+4

這是答案的一部分;你可能還想解釋如何在另一個JS文件中「包含」一個JS文件。 ['*咳嗽*'](http://requirejs.org/) – 2012-03-21 20:50:55

+0

謝謝您的回覆。我已經刪除了標籤(在上面的代碼中編輯過),但它仍然不起作用。 – 2012-03-21 20:53:57

+0

@ user996035查看'bottom.js'內容的更新回答。 – 2012-03-21 20:57:57

0

不要使用HTML標籤中.js文件。只是普通的javascript代碼

+0

謝謝你的回覆。我已經編輯了上面的代碼以包含您的建議,但似乎仍然無法正常工作。 – 2012-03-21 20:53:04

+0

您不能在定義其他'.js'文件的'.js'文件中使用函數。所有必須在兩個js必須鏈接的html中使用 – safarov 2012-03-21 20:56:43