Use current elements class as an array name?
Is it possible to use a string from an elements CSS class as an array name?
I'm looking for a smarter way of storing default animations that may grow over time to include more options 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!
You can access a global (top-level) variable by name using:
window[arr]
So you're looking for window[arr][0]
. See it in action here: http://jsbin.com/ofemo
However, this creates close linkage between your JavaScript and design. I usually prefer to use .addClass
, and define the colors using CSS.
You should use jQuery's meta-data plugin. It allows you to store any element-related data in class or any data-* attribute.
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')]);
精彩评论