我剛開始定義和實現外部的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>
這是答案的一部分;你可能還想解釋如何在另一個JS文件中「包含」一個JS文件。 ['*咳嗽*'](http://requirejs.org/) – 2012-03-21 20:50:55
謝謝您的回覆。我已經刪除了標籤(在上面的代碼中編輯過),但它仍然不起作用。 – 2012-03-21 20:53:57
@ user996035查看'bottom.js'內容的更新回答。 – 2012-03-21 20:57:57