从模块构建 jQuery DOM 个元素

Building jQuery DOM elements from a module

我真的很喜欢将我的代码模块化到单独的文件中,通常是因为我写的东西应该能够接受一些参数,然后很容易地附加到任何人页面上的 DOM 元素。这些模块通常是网络拓扑之类的图形表示,这需要大量的 div 和相当数量的参数。

我的问题是在构建 DOM 结构时(例如,当不谈论表格的 100 行时)最好的方法是什么?这些是我自己的路线,我仍在努力确定哪一条是最好的。

作为弦乐片段


var myModule1 = function (options) {
    this.userContainer = options.container;
    this.wrapper = '<div class = "mm1-wrapper"/>';
    this.piece1 = '<div class = "mm1-piece1"/>';
    this.piece2 = '<div class = "mm1-piece2"/>';
    this.piece3 = '<div class = "mm1-piece3"/>';
}

myModule1.prototype.build = function () {
    var wrap = $(this.wrapper).append(this.piece, this.piece2, this.piece3, );
    this.userContainer.append(wrap);
}

作为 jQuery 件在 collection


var myModule2 = function (options) {
    this.userContainer = options.container;
    this.wrapper = $('<div class = "mm1-wrapper"/>');
    this.peices = {
        1: $('<div class = "mm1-piece1"/>'),
        2: $('<div class = "mm1-piece2"/>'),
        3: $('<div class = "mm1-piece3"/>')
    }
}
//Using an each loop to append
myModule2.prototype.build = function () {
    $.each(this.piece, function (i, e) {
        this.wrapper.append(e);
    });
    this.userContainer.append(this.wrapper);
}

我只是在寻找关于

的一些见解

1) 将东西存储为 jQuery objects 是否占用大量资源?

2) 在 collection 中存储大块是否占用大量资源?

3) 这就是我创建模块的方式,但我显然对它们不放心。这个结构有意义吗?

回答您的问题:

1- 不是真的

2- 不是真的

3- 如果它对您有用并且您已经有了一些工作,那么请不要担心。

当然,我强烈建议您查看 Angular or React

这样的框架

您可以将 html 模板中的逻辑拆分到不同的文件中。 Imo,调试 html 文件比调试 javascript 文件中的字符串列表更干净、更容易。学习曲线是严酷的,但非常值得。

检查 ng-Repeat 是否有 angular。

干杯!