如何拆分javascript& html到多个文件

时间:2012-02-23 08:30:11

标签: javascript html file

我正在使用PHP,HTML& jQuery的。让我们说这是我原来的工作“index.html”

<script type="text/javascript" src="jquery.js"></script>
<script>
var p1 = "This is part 1";
var p2 = "This is part 2";
$(document).ready(function(){
    alert(p1);
    $('#content').html(p2);
});
</script>
<div id="content"></div>
<div id="content2">Hello</div>

我想将代码分解为“index.html”&amp; “otherFile.notSureWhatExt”但它们就像在同一个文件中一样工作。

的index.html:

<script type="text/javascript" src="jquery.js"></script>
<script type="notSureWhatType" src="otherFile.notSureWhatExt"></script>
<script>
var p1 = "This is part 1";
$(document).ready(function(){
    alert(p1);
});
</script>
<div id="content"></div>

otherFile.notSureWhatExt:

<script>
var p2 = "This is part 2";
$(document).ready(function(){
    $('#content').html(p2);
});
</script>
<div id="content2">Hello</div>

使用jsp,我只需使用&lt;%@ include file =“otherFile.anyCustomExtAlsoWorks”%&gt;。但我现在不在这里。我想要的是当调用index.html时,我可以看到消息框“这是第1部分”,底部有2个div,即“这是第2部分”&amp; “你好”。

3 个答案:

答案 0 :(得分:2)

您可以将javascript放在.js文件中。

。不需要脚本标记

然后您可以将其包含在

<script type="text/javascript" src="otherFile.js"></script>

答案 1 :(得分:0)

扩展程序应为.js,并从该文件中删除&lt; script&gt; -tags。

类型为text/javascript - 但没有必要,因为浏览器会忽略它。

答案 2 :(得分:0)

我认为可以通过“服务器端包含”来完成。你使用PHP的任何方式,所以你可以使用PHP。但是这里的file1.php或file1.html可以包含在file2.php中。这是一个php / html文件,可以包含在一个php文件中,但不能在另一个html中包含一个html。您可以浏览以下链接:http://webdesign.about.com/od/ssi/a/aa052002a.htmhttp://www.boutell.com/newfaq/creating/include.html,甚至还有一次讨论 How to include one HTML file into another?