通过“each”创建对象并自动命名它们
Creating Objects via "each" and automatically name them
我试图"读取"dom元素,然后在对象中存储它们的一些值。它基本上是工作的,但我想知道如何正确地命名它们(例如根据它们的索引)。我喜欢像"element0"这样的东西。"、"element1字符串。字符串"等。你认为正确的方法是什么?
function Element(index, el, height, string) {
this.el = el;
this.height = height;
this.string = string;
this.index = index;
}
$(".element").each(function(){
var el = $(this);
var height = $(this).height();
var index = $(this).index();
var string = "Foobar";
element = new Element(index, el, height, string);
});
alert(element.index);
您将使用each
方法附带的索引参数:
$('.element').each(function(i) {
// your code
window['element'+i] = new Element( /* etc. */ );
});
基本上,您将索引参数与连接的变量名一起使用。因为全局变量通常属于window
对象,你可以直接访问window
对象并添加一个属性(即你的全局变量)给它。
编辑
正如下面的评论者所说,最好的方法可能是将所有新创建的对象扔到一个数组中:
var elements = [];
// your code
elements.push(new Element());
这将允许您像这样访问每个新对象:
elements[0]; // => your first element
这是一种更常见的方式,看起来更模块化和干净。
每个函数中都有元素和索引
引用这
应该这样使用
$(".element").each(function(index,elem){
var height = $(elem).height();
var string = "Foobar";
element = new Element(index, $(elem), height, string);
});
相关文章:
- 在创建对象后附加一个jquery事件
- 错误:自动化服务器可以't创建对象
- 如何在不使用 new 关键字的情况下从函数创建对象
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- 创建对象函数原型和代码是错误的
- 使用Undercore创建对象集合
- 如何在JavaScript中创建对象时使用变量的值
- 正在创建对象的递归列表
- 这两种不同的创建对象文字的方法有什么区别
- ES6 const,用于在JavaScript中创建对象原型;这是一种模式吗
- 使用字符串作为名称创建对象
- 使用参数创建对象
- 如何在JS中创建对象的可变和不可变副本
- 用javascript创建对象的dynamic数组
- Javascript,用vars创建对象的最佳方法
- 离子幻灯片框中未创建对象
- 如何在jquery中从$.each循环创建对象数组
- 读取 json 以使用 jQuery .each() 创建对象数组
- jQuery .each()创建对象数组
- 通过“each”创建对象并自动命名它们