Use current element class as array name?

Is it possible to use a string from a CSS class as an array name?
I'm looking for a smarter way to store default animations, which can increase over time to include more parameters in the array.

Example


JavaScript (jQuery): -

var a1 = ['red', 'pink']; 
var a2 = ['green', 'lime']; 
var a3 = ['blue', 'cyan']; 

$('ul li').click(function() { 
    arr = $(this).attr('class');    // Does this need to be converted?
    $('div#sprite').css('background', arr[0]);    // Is this kosher?
    $('div#sprite p').css('color', arr[1]); 
    });  

HTML: -

<div id='sprite'><p>Lorem ipsum...</p></div>

<ul>
    <li class='a1'>Array 1</li>
    <li class='a1'>Array 2</li>
    <li class='a1'>Array 3</li>
    </ul>

Thanks in advance!

+3
source share
3 answers

You can get the global (top) variable by name using:

window[arr]

So you are looking window[arr][0]. See here in action: http://jsbin.com/ofemo

JavaScript . .addClass CSS.

+2

jQuery. data- *.

+2

Alternatively, have an array like this:

var colors = {
    'a1':{
        'background-color':'red',
        'color':'pink'
    },
    'a2':{
        'background-color':'green',
        'color':'lime'
    },
    'a3':{
        'background-color':'blue',
        'color':'cyan'
    }
}

and then

$('div#sprite').css(colors[$(this).attr('class')]);
+2
source

Source: https://habr.com/ru/post/1727927/


All Articles