-4

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;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Not Amused
  • 942
  • 2
  • 10
  • 28
  • 1
    You have typo... it's not programming question... – Karol May 15 '13 at 23:43
  • Please stop downvoting, this one question costed me the right to ask another question on this forum. I didn't post the question lightly. I did check the code before i do that. You never had a typo that you just couldn't see? Thank you. – Not Amused Apr 02 '14 at 21:15

1 Answers1

1

You made a typo:

var imgSrc = 'ulr(./FoodImages/fruit' + i.toString() + '.jpg)';
               ^^

Change that to url(...)

Also the .toString() should not be necessary

jabbink
  • 1,271
  • 1
  • 8
  • 20