【问题标题】:How to split javascript & html into multiple files如何将javascript和html拆分为多个文件
【发布时间】:2012-03-13 15:31:24
【问题描述】:

我正在使用 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,我可以简单地使用。但我现在不在这里。我想要的是在调用 index.html 时,我可以看到消息框“这是第 1 部分”和底部的 2 个 div,即“这是第 2 部分”和“你好”。

【问题讨论】:

    标签: javascript html file


    【解决方案1】:

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

    然后您可以将其包含在

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

    【讨论】:

    • 不知何故它不起作用。当我在 otherFile 中执行 alert(p1) 时,萤火虫说 p1 未定义
    【解决方案2】:

    我认为可以通过“服务器端包含”来完成。您使用 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?

    【讨论】:

      【解决方案3】:

      扩展名应该是 .js 并从该文件中删除

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

      【讨论】:

      • 我已经完善了我的问题以便更好地理解。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2017-02-27
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多