How to change the background image of a button using JavaScript?

徘徊边缘 提交于 2019-12-09 03:39:22

for (... in ...) loops do not work that way in JavaScript it should be:

for (var b = 0; b < buttons.length; b++) {
    buttons[b].style.backgroundImage = "url('darkSquare.jpg')";
}

for (... in ...) actually iterates over all the "members" of an object

eg. using var x = {a: 1, b: 2, c: 3} in for(var m in x) console.log(m) will produce

> a
> b
> c

it kind of works with arrays because it considers the indices members like this:

var x = [1,2,3];
for (var m in x) console.log(m);
> 0
> 1
> 2

since it is giving you the indices as if they were members you can't distinguish. the pitfall is:

var x = [1,2,3];
x.stuff = 'boo!';
for (var m in x) console.log(m);
> 0
> 1
> 2
> stuff

General Rule of Thumb: only use for (... in ...) when iterating over members in an object, use for (var i = 0; i < array.length; i++) when using arrays

you can always cheat and use:

for (var i = 0, item = x[i]; i < x.length; item=x[++i]) {
    // now item is the current item
}

You should change your loop as so

for(var i = 0; i < buttons.length; i++)
{
   buttons[i].style.backgroundImage = "url('darkSquare.jpg')";
}​

The loop you used assign keys in a variable b. Since you didn't use the hasOwnProperty function, this loop can also yield other data you might not want.

You could also use the for-in loop as so

for(var b in buttons)
{
    if (buttons.hasOwnProperty(b))
        buttons[b].style.backgroundImage = "url('darkSquare.jpg')";
}​

when using for ( ... in .... ) the first parameter is the key in the array so you have to use it like this:

for( b in buttons ) {
    buttons[b].style.backgroundImage = "url('darkSquare.jpg')";
}

working example in jsFiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!