使用模块模式时如何将 jquery 源代码拆分成多个文件?

How to split jquery source code into multiple files when using the module pattern?

我在将 jquery 源代码拆分到多个文件时遇到了一些问题。我的真实源代码有点复杂,但下面的简单示例很好地说明了我的问题。首先,我想向您展示一个只有一个 javascript 文件的工作示例。之后,我将描述我为将 javascript 拆分为两个文件所做的尝试。

我的 html 代码如下所示("./jquery" 是我本地 jquery 下载的符号 link):

<html>
  <head>
    <script src="./jquery"></script>
    <script src="./file1.js"></script>
  </head>

  <body>
    <div id="content"></div>
  </body>
</html>

file1.js 中的 jquery 源代码如下所示:

$(document).ready(function() {

  var Test = (function() {
    var content = $('#content');

    var init = function() {
      content.html('<p>test</p>');
    };

    return {
      init: init
    }
  })();

  Test.init();
});

打开页面后,显示"test",这样这个例子就可以正常运行了。

但现在我想把整个测试部分放到另一个文件中file2.js。我的 html 基本相同,但多了一行:

<script src="./file2.js"></script>

file1.js 现在只包含初始化函数的调用:

$(document).ready(function() {
  Test.init();
});

和file2.js包含测试的定义:

var Test = (function() {
  var content = $('#content');

  var init = function() {
    content.html('<p>test</p>');
  };

  return {
    init: init
  }
})();

当我打开页面时,"test"不再显示。为了确保调用 init 函数,我添加了一个 console.log("test");到工作正常的 init 函数。因此,我认为该函数可能会在 DOM 准备好之前被调用,但实际上我很无能。也许有人可以给我提示如何制作 运行.

提前致以最诚挚的问候和感谢!

file1 依赖于 file2。确保 file1 在 html.

中按顺序出现在 file2 之后

修改你的file2.js如下:

var Test = {
  content : $('#content'),
  init : function() {        
    Test.content.html('<p>test</p>');
  }
  //, include other functions here
};

修改你的file1.js如下:

$(document).ready(function(){
   Test.init();
})

现在在声明 file1.js 之前声明 file2.js 因为 file1.js 正在引用来自 file2.js 的函数。

AngularJS 提供依赖注入、模块、服务、工厂和各种其他优点。需要一点时间来适应,但非常值得 IMO:从 DOM 中更清晰地抽象 javascript,从演示文稿等中提取数据

感谢您的问题 JQuery 具体,但特别是如果您要开始一个新网站,我建议您尝试 Angular。

您可以根据自己的喜好做几件事... 1. 将脚本移动到 HTML 文件的末尾而不是 header...

<html>
  <head>
  </head>

  <body>
    <div id="content"></div>
  </body>
  <script src="./jquery"></script>
  <script src="./file2.js"></script>
  <script src="./file1.js"></script>
</html>

安全地考虑这个问题...如果您不想在引用 DOM 中的元素的每个模块中声明一个 var,您需要该元素首先存在,然后您可以声明 "global" var 到模块 content。这样你原来的 file2.js 就可以了。

另一种方法是向您的模块声明内容"global",但在您的初始化函数中初始化它...

var Test = (function() {
  var content;

  var init = function() {
    content = $('#content');
    content.html('<p>test</p>');
  };

  return {
    init: init
  }
})();

现在您可以在模块的所有函数中使用内容变量。

希望这对您有所帮助,请告诉我。