I'm trying to change the background images of table cells with Javascript and I do so by creating the name of the image inside the code using the counter index in a for loop (i)
This doesn't work, can somebody explain why and how to do it properly? If I put a static image name it works, if I try dynamically it doesn't.
This Doesn't work:
var tbl = document.getElementById('SelectionBoard');
var cells = tbl.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++)
{
cells[i].addEventListener('click', sbClick, false);
var imgSrc = 'ulr(./FoodImages/fruit' + i.toString() + '.jpg)';
cells[i].style.backgroundImage=imgSrc;
}
This does:
var tbl = document.getElementById('SelectionBoard');
var cells = tbl.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++)
{
cells[i].addEventListener('click', sbClick, false);
var imgSrc = 'url(./FoodImages/fruit3.jpg)';
cells[i].style.backgroundImage=imgSrc;
}
You made a typo:
var imgSrc = 'ulr(./FoodImages/fruit' + i.toString() + '.jpg)';
^^
Change that to url(...)
Also the .toString() should not be necessary