代码之家  ›  专栏  ›  技术社区  ›  Tom Gullen

Javascript无法设置颜色

  •  0
  • Tom Gullen  · 技术社区  · 13 年前

    函数通过以下方式调用:

    myChart.gChangeBarColour(1, "#000000");
    

    这是有效的:

       // Changes bars colour
        this.gChangeBarColour = function(gBarID, gBarColour) {
    
            if (gBarID <= this.gData.length && gBarID >= 0) {
    
                document.getElementById("gBar" + gBarID).style.backgroundColor = '#000000';
    
            }
    
        }
    

    但这不管用:

    // Changes bars colour
    this.gChangeBarColour = function(gBarID, gBarColour) {
    
        if (gBarID <= this.gData.length && gBarID >= 0) {
    
            document.getElementById("gBar" + gBarID).style.backgroundColor = '" + gBarColour + "';
    
        }
    
    }
    

    控制台没有任何错误!有什么想法吗?

    2 回复  |  直到 13 年前
        1
  •  7
  •   Ivo Wetzel    13 年前

    你的 '" + gBarColour + "' 是一个 string ,由单引号分隔 ' 包含 " + gBarColour + " ,然后将该值用作颜色。

    你需要去掉所有的引号和加号:

    // assign the value of gBarColour to the backgroundColor property
    document.getElementById("gBar" + gBarID).style.backgroundColor = gBarColour;
    
        2
  •  1
  •   switz    13 年前
    '" + gBarColour + "'
    

    应该是

    gBarColour ''+gBarColour