Okay, so .stockitemsimgrow
is the start of each image numbering cycle.
I’ll use the modified div structure that you supplied.
Let’s work through how to modify the scripting code to achieve that. Here’s the existing code:
jQuery(function ($) {
$(".stockitemsimg").each(function (index, itemsimg) {
$("img", itemsimg).attr("src", index + ".jpg");
});
});
We want the .stockitemsimg
selection to be restricted to each .stockitemsimgrow
section, so the first jQuery selector can be restricted based on that:
$(".stockitemsimg", itemsimgrow).each(...
And we can wrap that code with another selector loop that gives us itemsimgrow:
$(".stockitemsimgrow").each(function (ignore, itemsimgrow) {
...
});
I now want to use those index numbers for the image names, and presume that you want to reference that information from an array. Unless you want each set of images to be identical, we’ll want to make use of the s1
and s2
parent id to help us group the images together.
How we best achieve that is to start from the array/object structure, and modify the code to work with that structure.
var images = [
{
id: "s1",
imgs: [
"http://www.iconsplace.com/download/aqua-number-1-128.ico",
"http://icons.iconarchive.com/icons/icons8/windows-8/128/Numbers-2-icon.png"
]
},
{
id: "s2",
imgs: [
"https://v.fastcdn.co/u/12116475/23083356-0-one.png",
"http://neslearningzone.com/wp-content/uploads/2016/11/year-2.png"
]
}
];
We can now filter for the id, and get the appropriate image:
$(".stockitemsimgrow").each(function (ignore, itemsimgrow) {
var id = $(itemsimgrow).parent().attr("id");
var imgs = images.find(function (imageInfo) {
return imageInfo.id === id;
}).imgs;
and the imgs
variable now contains an indexed list of images to use.
We can now rename index + ".jpg"
so that it gets the image from the array instead:
$("img", itemsimg).attr("src", imgs[index]);
and we now have working code that sets the image to the images stored in the array/object structure.
The full scripting code is:
var images = [
{
id: "s1",
imgs: [
"http://www.iconsplace.com/download/aqua-number-1-128.ico",
"http://icons.iconarchive.com/icons/icons8/windows-8/128/Numbers-2-icon.png"
]
},
{
id: "s2",
imgs: [
"https://v.fastcdn.co/u/12116475/23083356-0-one.png",
"http://neslearningzone.com/wp-content/uploads/2016/11/year-2.png"
]
}
];
jQuery(function ($) {
$(".stockitemsimgrow").each(function (ignore, itemsimgrow) {
var id = $(itemsimgrow).parent().attr("id");
var imgs = images.find(function (imageInfo) {
return imageInfo.id === id;
}).imgs;
$(".stockitemsimg", itemsimgrow).each(function (index, itemsimg) {
$("img", itemsimg).attr("src", imgs[index]);
});
});
});
and a working example is found at https://jsfiddle.net/bvmny207/1/