Ramon
Ramon

Reputation: 1

Get a variable name from .attr

I have 2 blocks

<div data-array="array1" class="div-to-click">DIVtoClick</div>

<div class="div-to-append"></div>

and have an array

array1 = [ 1, 2, 3, 4, 5 ];

Can I somehow get a name of variable from .attr('data-array') onclick and do something like

array1.forEach(function( elem ){
    $('div-to-append').append( '<div class="number">'+elem+'</div>' );
}); 

Upvotes: 0

Views: 53

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You could define your arrays as the properties of an object, then use bracket notation to retrieve them. Something like this:

var obj = {
    array1: [ 1, 2, 3, 4, 5 ],
    array2: [ 6, 7, 8, 9, 10 ]
}

$('.div-to-click').click(function() {
    $.each(obj[$(this).data('array')], function(i, item){
        $('div-to-append').append('<div class="number">' + item + '</div>');
    }); 
});

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59232

Attach it to a object. Making global is not advised, as the global context is getting polluted. So make your own object and

var myObj = {
   array1 = [ 1, 2, 3, 4, 5 ],
   //...
}

Then you could use bracket notation.

$('.div-to-click').click(function(){
   myObj[$(this).data("array")].forEach(function( elem ){
       $('div-to-append').append('<div class="number">' + elem + '</div>' );
   }); 
});

Upvotes: 2

Related Questions