2012-03-21 27 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