如何更改使用JavaScript的一个按钮的背景图像? [英] How to change the background image of a button using JavaScript?

查看:117
本文介绍了如何更改使用JavaScript的一个按钮的背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要改变使用Javascript按钮的背景图像。以下是我目前努力,但它失败。

I want to change the background image of a button using Javascript. Here is what I am currently trying, but it is failing.

HTML code -

HTML code -

      <tr id="Rank1">
              <td><button class="darkSquare"></button></td>
               <td><button class="lightSquare" ></button></td>
                <td><button class="darkSquare" ></button></td>
               <td><button class="lightSquare" ></button></td>
                <td><button id="e1" class="darkSquare" ></button></td>
                <td><button class="lightSquare" ></button></td>
                <td><button class="darkSquare" ></button></td>
                <td><button class="lightSquare"> </button></td>
            </tr>

JavaScript的code

JavaScript Code

        initializer();

        function initializer()
         {
           var tableRow = document.getElementById("Rank1");

           var buttons = tableRow.getElementsByTagName("button");

           for(b in buttons)
            {
               console.log(b.toString());
               b.style.backgroundImage = "url('darkSquare.jpg')";
            }
         }

在控制台中,我得到一个错误说b.style是不确定的。

In the console, I get an error saying b.style is undefined.

推荐答案

为(... ...中)循环不工作在JavaScript中这样,它应该是:

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

如。使用 VAR X = {A:1,B 2,C:3} 的(在X VAR米)的console.log(M) 将产生

> 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

一般的经验法则:只使用为(... ...中)在对象遍历成员时,,使用为(VAR I = 0; I&LT; array.length,我++)使用数组时

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

你总是可以欺骗和使用的:

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

这篇关于如何更改使用JavaScript的一个按钮的背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆