字符串 JavaScript中的增量值



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

 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命名为错误。新手错误!:)

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)

相关内容

  • 没有找到相关文章

最新更新