如何拆分javascript&html转换为多个文件

How to split javascript & html into multiple files

本文关键字:转换 html 文件 amp 何拆分 拆分 javascript      更新时间:2023-09-26

我使用的是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"&"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,我可以简单地使用<%@include file="otherFile.anyCustomExtAlsoWorks"%>。但我现在没有。我想要的是,当调用index.html时,我可以看到消息框"This is part 1"和底部的2div,即"This is part 2"&"你好"。

您可以将javascript放在.js文件中。不需要脚本标记。

然后您可以将其包含在中

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

我认为这可以通过"服务器端包含"来完成。使用php的任何方式都可以使用php。但这里的file1.php或file1.html可以包含在file2.php中。这是一个php/html文件可以包含在一个php文件中,但不能包含另一个html中的一个html。您可以通过以下链接:http://webdesign.about.com/od/ssi/a/aa052002a.htm和http://www.boutell.com/newfaq/creating/include.html甚至在如何将一个HTML文件包含到另一个文件中?

扩展名应为.js,并删除<script>-来自该文件的标记。

类型为text/javascript,但这不是必需的,因为浏览器会忽略它。