简体   繁体   中英

Creating Objects via “each” and automatically name them

I'm trying to "read" dom-elements, and then to store some of their values in Objects. It's bascially working, but I'm wondering how to name them properly (according to their index for instance). I'd love to have something like "element0.string", "element1.string" etc. Whats the right approach in your opinion?

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);

You'll use the index parameter that comes with the each method:

$('.element').each(function(i) {
    // your code
    window['element'+i] = new Element( /* etc. */ );
});

Basically you're using the index parameter in conjunction with a concatenated variable name. Since global variables usually belong to the window object, you can access the window object directly and add a property (ie your global variable) to it.

Edit

As the commenter below said, the best way might be to throw all your newly created objects into an array:

var elements = [];

// your code
    elements.push(new Element());

This will let you access each new object like this:

elements[0]; // => your first element

This is a more common way, and seems a little bit more modular and clean.

you have the elem and the index inside each function

refer this

you should use in this way

$(".element").each(function(index,elem){


    var height = $(elem).height();

    var string = "Foobar";

    element = new Element(index, $(elem), height, string);       

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM