0

Inside "myFunction", I have an each() iterator which finds the height of certain elements. How can I assign each height value to an incrementally generated variable name, accessible outside the each loop?

function myFunction(){

    $('#div1, #div2 ... #divN').each(function(index){
        /* Increment variable name here */ = $(this).outerHeight();
    });

    // Also use those variables here

};

Thanks.

4

3 回答 3

6

This task is better solved with an array, and thanks to jQuery's built-in methods, you can easily extract certain values from a set of elements to an array:

var heights = $('#div1, #div2 ... #divN').map(function(){
    return $(this).outerHeight();
}).get();
// `heights` is an array and
// heights[0] = height of first element in the tree
// heights[1] = height of second element in the tree
// ...

I have to stress that the order of the heights array is not the order in which you put the elements in the selector! jQuery will always reorder the elements to how they are positioned in the DOM.

Reference: .map, .get


If you want the height somehow associated to something which can identify the element, you can use an object where the keys are the element IDs and the values are the heights:

var heights = {};
$('#div1, #div2 ... #divN').each(function(){
    heights[this.id] = $(this).outerHeight();
});
// `heights` is an object and
// heights['div1'] = height of element with ID div1
// heights['div2'] = height of element with ID div2
// ...
于 2013-01-31T12:15:20.723 回答
2

You can use an array / object:

function myFunction(){

    var heights = [];

    $('#div1, #div2 ... #divN').each(function(index, value){
        heights[index] = $(this).outerHeight();
    });

    console.log(heights); // etc... etc...

};

You'll be able to access them like:

heights[1], heights[2] ... etc

于 2013-01-31T12:16:02.373 回答
2

If you really want named variables created dynamically (instead of using an array, as suggested in comments), you could either do something like

$('#div1, #div2 ... #divN').each(function(index){
    window['myVar' + index] = $(this).outerHeight();
}

which will create global variables named myVar0, myVar1...

If you don't want to pollute the global namespace like that, you could go:

var myVars = {};
$('#div1, #div2 ... #divN').each(function(index){
    myVars['var' + index] = $(this).outerHeight();
}

and access your variables like myVars.var0, myVars.var1...

于 2013-01-31T12:19:22.403 回答