【问题标题】:String + an incremental value in JavaScript字符串 + JavaScript 中的增量值
【发布时间】:2019-07-28 00:00:38
【问题描述】:

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

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

【问题讨论】:

  • 是的。我们肯定会帮助你。请添加一些工作示例或标记 html
  • 你得到的错误是什么?
  • if (starting = 2) 必须是 if (starting === 2)
  • 嗯,javascript 根本无法加载。我也试过这个:document.getElementById("btn" + i).style.backgroundColor = "red";
  • 工作正常:jsfiddle.net/khrismuc/efzdmk6a 您检查浏览器控制台是否有错误消息?编辑后编辑:听起来你需要var n = "btn" + (i + 2);

标签: javascript html web styles


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多