通过“each”创建对象并自动命名它们

Creating Objects via "each" and automatically name them

本文关键字:each 创建对象 通过      更新时间:2023-09-26

我试图"读取"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);       
    });