javascript - 如何将 javascript 和 html 拆分为多个文件

标签 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”和“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时,我可以看到消息框“这是第1部分”和底部的2个div,即“这是第2部分”和“你好”。

最佳答案

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

然后您可以将其包含在

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

关于javascript - 如何将 javascript 和 html 拆分为多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9409466/

相关文章:

javascript - 如何在Javascript中将两个数组添加到一个数组中

python - 我可以打印 HTML,就像在 python 中没有标签的网页中查看的那样吗?

c - 无法通过c程序复制二进制文件

string - 斯卡拉 : cleanest way to recursively parse files checking for multiple strings

java - getCanonicalFile 和 getAbsoluteFile 返回当前(项目)目录,而不是预期的目录

javascript - (好奇)- 拥有顶级智能组件或小型连接组件更好?

javascript - Karma 如何通过 id 加载模块?

javascript - 如何使用 javascript 显示来自 parse.com 数据库的图像?

python - 在Python中迭代HTML中的 "class"属性?

python - 如何防止 LXML 错误 'failed to load external entity'