Is it possible to bind JavaScript data to HTML elements?

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];

I need to do another piece of information and attach it to the body tag. So. if test1.jpg is loaded, I need to transfer β€œlight” to the body of the body, and if another image is selected, I need to transfer β€œdark”. This means that the user in CMS chooses a light or dark theme depending on the image. The image will be displayed randomly.

+3
source share
4 answers

Like 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];
0
source

You can store objects in your array:

// I'm using an Array literal instead of a Array constructor here, because it 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;
+4
source

.

var img_name = new Array("images/test.jpg:light", "images/test.jpg:dark");

: . seperator : .

0

You can use the srcs string image map for topic names. You can then use the selected src image to directly access the topic name.

var themeMap = {};
themeMap["testImg1.jpg"] = myDarkTheme; //myDarkTheme can be a full object or just a string

Then you can do

getTheme(img_name[rnd_no]);

function getTheme(imgSrcString)
{
    return themeMap[imgSrcString];
}
0
source

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


All Articles