I have an array (below)
var img_name = new Array("images/test.jpg", "images/test.jpg");
var imgTotal = img_name.length;
var rnd_no = Math.floor(imgTotal*Math.random());
var ojimg = img_name[rnd_no];
开发者_StackOverflow社区What I need to do is pass another piece of information and attach that to the body tag. So. if test1.jpg is loaded I need to pass "light" to the body tag and if the other image is selected I need to pass "dark". What this does is alows a user in CMS to select a light or dark theme depending on the image. The image will be output randomly.
You could store objects in your array:
// I'm using an Array literal instead of a Array constructor here, because it's shorter
var img_name = [ {image:"images/test.jpg", style:"light"}, {image:"images/test.jpg", style:"dark"} ];
var imgTotal = img_name.length;
var rnd_no = Math.floor(imgTotal*Math.random());
var ojimg = img_name[rnd_no].image;
var ojstyle = img_name[rnd_no].style;
How about nested arrays:
var img_name = [["images/test1.jpg", "light"], ["images/test2.jpg", "dark"]]];
var imgTotal = img_name.length;
var rnd_no = Math.floor(imgTotal*Math.random());
var ojimg = img_name[rnd_no][0];
var cssclass = img_name[rnd_no][1];
In your array, you can just have some additional string with a seperator.
var img_name = new Array("images/test.jpg:light", "images/test.jpg:dark");
For your example, I have used :
as seperator. In the consuming method, you can split the data based on seperator :
and use both items accordingly.
You could use a map of image srcs strings to theme names. Then you can use a selected image src to directly access the theme name.
var themeMap = {};
themeMap["testImg1.jpg"] = myDarkTheme; //myDarkTheme can be a full object or just a string
You can then do
getTheme(img_name[rnd_no]);
function getTheme(imgSrcString)
{
return themeMap[imgSrcString];
}
精彩评论