简体   繁体   English

如何在JavaScript中将backgroundColor分配给var

[英]How to assign backgroundColor to a var in JavaScript

seems like a simple question but I don't know JavaScript too well and my search-fu is turning up nothing relevant. 似乎是一个简单的问题,但我对JavaScript不太了解,而且我的搜索功能没有任何意义。

I need to set the backgroundColor property of a textbox to a value set as a String in a var, like so: 我需要将文本框的backgroundColor属性设置为在var中设置为String的值,如下所示:

var pinColor = someFunctionThatReturnsString();
document.getElementById("pin").style.backgroundColor = pinColor;

If I put a literal there instead of a var, like '#ffff00', then it works fine. 如果我在此处放置文字而不是var,例如“#ffff00”,则它可以正常工作。 However a var with the String value '#ffff00' does not work (causes no error but does not set the background either). 但是,具有字符串值'#ffff00'的var不起作用(不会引起错误,但也不会设置背景)。 I have to use a var for the assignment because the information is coming from somewhere else, but I can't figure out how to make the backgroundColor respect a String value. 我必须使用var进行赋值,因为信息来自其他地方,但是我不知道如何使backgroundColor尊重String值。 Is there some conversion I have to do? 我需要做些转换吗?

Thank you! 谢谢!

Is there some conversion I have to do? 我需要做些转换吗?

No, there isn't. 不,没有。 It doesn't matter if you use a string literal or a variable. 使用字符串文字还是变量都没关系。

You have misdiagnosed the problem. 您误诊了问题。

See a live example . 看到一个真实的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM