Hi there, I am in a bit of a situation. I have a few images that I have inserted in my html using javascript. The url of the images are stored as strings in json object notation and to access them in the script I had to have 2 nested for in
loops.
Now, the relevant code in the function is this:
function populateHTML(booleanVar){
...
for(i in whatever ){//accessing the top of json
for(j in whatever[i]){////accessing second level of json where the images are
if(booleanVar){
myHTML += '<div id="myImages"><a href="javascript:void(0)"><img src="' + whatever[i][j].thumb + '" data-value="' + bestVal + '"alt="" ></a></div>';
}
else{
...
}
}
}
So I end up in a situation like the below.
...
<div id="myImages">
<img src="image1.jpg" data-value="10">
<img src="image2.jpg" data-value="11">
<img src="image3.jpg" data-value="12">
<img src="image4.jpg" data-value="13">
<img src="image5.jpg" data-value="14">
<img src="image6.jpg" data-value="15">
<img src="image7.jpg" data-value="16">
</div>
...
Now the first time the page load I have a boolean variable set to true so that this bit
{myHTML += '<div id="myImages"><a href="javascript:void(0)"><img src="' + whatever[i][j].thumb + '" data-value="' + bestVal + '"alt="" ></a></div>';
runs and populate the html with images. After that I call populateHTML()
from somewhere else passing booleanVar
as false because I don't want to re-insert the images but just update their data-value attribute which will be done in the above else{}
statement but this turned out to be a nightmare.
In the else statement - let's not forget we are in a loop still - I need to access the data-value of each image and change it. I have tried different ways to access the current image but I don't seem to be able to do it. Few of my attempts were:
else{
$("vehicle_row a img").attr("data-value", bestVal);
...
and then I tried this
else{
$("vehicle_row a img").data("value") === bestVal;
...
but I have a feeling that the above don't select the current version of the image. Is there any such a selector as $("vehicle_row a this.img")...
which allows me to select the current image?
Any suggestion will be much appreciated. One thing only: the code above is just an extract. The whole function is about 100 lines and I didn't copy the whole thing because it isn't necessarily relevant to what I am trying to achieve. Also I can't really re-engineer it,so I will need to go with what I have
thanks