Javascript无法设置颜色

Tom*_*len 0 javascript function object

该功能通过以下方式调用:

myChart.gChangeBarColour(1, "#000000");
Run Code Online (Sandbox Code Playgroud)

这有效:

   // Changes bars colour
    this.gChangeBarColour = function(gBarID, gBarColour) {

        if (gBarID <= this.gData.length && gBarID >= 0) {

            document.getElementById("gBar" + gBarID).style.backgroundColor = '#000000';

        }

    }
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

// Changes bars colour
this.gChangeBarColour = function(gBarID, gBarColour) {

    if (gBarID <= this.gData.length && gBarID >= 0) {

        document.getElementById("gBar" + gBarID).style.backgroundColor = '" + gBarColour + "';

    }

}
Run Code Online (Sandbox Code Playgroud)

控制台完全没有错误!有任何想法吗?

Ivo*_*zel 7

'" + gBarColour + "' 的a是string'包含的单引号分隔的" + gBarColour + ",然后将该值用作颜色.

你需要省略所有引号和加号:

// assign the value of gBarColour to the backgroundColor property
document.getElementById("gBar" + gBarID).style.backgroundColor = gBarColour;
Run Code Online (Sandbox Code Playgroud)