字符串+ JavaScript中的增量值

时间:2019-03-06 10:42:01

标签: javascript html web styles

我在代码中间添加了注释。请帮助我,如果可以的话,我今天必须交付产品。

 if (a === 3) { //this would be how many of the answers further the action
                 var starting = 2; // for an example: yes or no; two of the answers go to no, one goes to yes. 
                 //                                  we take 2 as a starting point /you can set these individually for each scenario;
                 if (starting === 2) {
                     for (i = 0; i < starting; i++) {
                         answers[i] = 1; //sets the two checking points of the answer to the no, remaining yes;

 document.getElementById("btn" + i).style.backgroundColor = "red";

     // the problem lies here
    // I tried multiple ways but none of them worked so far
    //i want to apply the style change to multiple buttons at once.

                     }

                     alert(answers);

                     for (i = 0; i < starting; i++) {
                         if (answers[i] == 1) {

                         }
                     }

                 }
             }

问题在于按钮的名称为btn,并且按钮的名称分别为btn1,btn2,btn3;我希望for循环将其更改为所有按钮,但是id处的字符串文字无法识别i;

例如:“ btn” + i; =更改btn1的样式

我修复了。错误是for循环从1开始; 而且我将按钮的ID命名错误。新手出错! :)

1 个答案:

答案 0 :(得分:0)

for (i = 0; i < 3; i++) {
  if (document.getElementById("btn" + i) != undefined)
    document.getElementById("btn" + i).style.backgroundColor = "red";


}
<input type="button" value="Submit" id="btn3">
<input type="button" value="Submit" id="btn1">
<input type="button" value="Submit" id="btn2">

问题是您的按钮ID从 btn1 开始,代码从 0 开始(该位置不在您的html中),因此可以在设置背景颜色之前添加检查或启动您从1开始的循环

  

if (document.getElementById("btn" + i) != undefined)