JavaScript获取然后更改类(带变量)

时间:2017-02-26 21:36:27

标签: javascript class getelementbyid

我需要更新按钮以显示该组所处的最后状态,即判断1得分为0.我有四组6个按钮。输入所有分数后,我正在提交分数。我想显示最后得分在哪里。
enter image description here

我的问题是从两个for循环中抓取类。控制台告诉我:

  

未捕获的TypeError:无法读取null的属性“className”       在updateJudgeLast(scripts.js:278)

这是我的功能:

function updateJudgeLast(){
    for(j=1;j<5;j++){
        for(i=0;i<6;i++){
            var judgeScore ="#btnJudge";
            judgeScore += j;
            judgeScore += "_";
            judgeScore += i;
            console.info(judgeScore);

            var testLast = document.getElementById(judgeScore).className.split(' ')[1];
            console.info(testLast);

            switch(testLast){
            case "btn-default": break;
            case "btn-last":  $(judgeScore).attr("class", "btn btn-default"); break;
            case "btn-primary": $(judgeScore).attr("class", "btn btn-last"); break; 
            }
        }
    }
}

judgeScore是元素的id,用于获取它将输出的循环内部类:"#btnJudge1_0"然后"#btnJudge1_1"。当我检查控制台时它正确打印但无法检查它是否为null。我错过了什么?

背景:这是我正在制作的评分板,它在ESP8266 12e上运行FastLED,代码使用JSON和JS根据需要更新页面和电路板。

1 个答案:

答案 0 :(得分:2)

如果您要使用document.getElementById,则ID不应以'#'开头。试试这个:

var judgeScore ="btnJudge";  // remove #
    judgeScore += j;
    judgeScore += "_";
    judgeScore += i;
var testLast = document.getElementById(judgeScore).className.split(' ')[1];

或者使用document.querySelector并保持'#'像这样:

var judgeScore ="#btnJudge";  // keep #
    judgeScore += j;
    judgeScore += "_";
    judgeScore += i;
    console.info(judgeScore);
var testLast = document.querySelector(judgeScore).className.split(' ')[1]; // and use querySelector