This is obviously a totally inefficient way to change the background color of a button, but I'm wondering why this doesn't work:
<button id="blueButton">Button</button>
var data = {};
function changeColor(e){
data.e = "blue";
$('#' + e).css('background-color', data.e);
}
changeColor(blueButton);
If a variable is able to be used inside of a string (e.g. ${variable}
) why wouldn't it be able to be used in the above scenario?
To set the key of an object by a variable you need to use bracket notation:
Keep in mind that javascript allows only string
or Symbol
as Object
key. If you want to use some other type to key you need to have a look at Map
var data = {};
function changeColor(e){
data[e] = "blue";
$('#' + e).css('background-color', data[e]);
}
changeColor(blueButton);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With