我真的很喜欢将我的代码模块化到单独的文件中,通常是因为我正在编写的东西应该能够接受一些参数,然后轻松地最终附加到任何人页面上的 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 片段
<小时/>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 对象会占用大量资源吗?
2)在集合中存储大块资源是否会占用大量资源?
3)这就是我创建模块的方式,但我显然对它们缺乏安全感。这个结构有意义吗?
最佳答案
回答您的问题:
1- 并非如此
2- 并非如此
3-如果它对你有用并且你已经有了一些有用的东西,那就不用担心。
当然,我强烈建议您研究像Angular这样的框架。或React
您可以将逻辑从 html 模板中拆分到不同的文件中。我认为,调试 html 文件比调试 javascript 文件中的字符串列表更干净、更容易。学习曲线很严酷,但非常值得。
检查ng-Repeat对于 Angular 。
干杯!
关于javascript - 从模块构建 jQuery DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28766468/