Why this variable does not pass correctly in jQuery

I have a simple jQuery expression ... and my question is: why is one of them happening in the world?

Assume the variable colorAttributeis equal tocolor

    $(thisCLass).css( "color", '#'+hex ); // Works when written
    $(thisCLass).css( colorAttribute, '#'+hex ); // Works with variable

    $(thisCLass).css({ "color" : '#'+hex }); // Works when written  
    $(thisCLass).css({ colorAttribute : '#'+hex }); // Does not Work with variable

Any ideas as to why this is failing?

+3
source share
7 answers

This is because you cannot use a variable to indicate a name in an object literal.

The identifier in the object literal can be written with or without quotation marks, so it will not be interpreted as a variable in any case. The object will contain the identifier you specified:

{ "colorAttribute" : '#'+hex }

You can use a variable to set a property in an object, but then you need to create the object first and use the bracket syntax:

var obj = {};
obj[colorAttribute] = '#'+hex;
$(thisCLass).css(obj);
+5

, JavaScript. , . , , .

:

var cssProps = {};
cssProps[colorAttribute] = '#' + hex;
$(thisClass).css(cssProps);
+4

: "colorAttribute".

:

myobj = {};
myobj[collorAttribute] = "#"+hex;
$(thisClass).css(myobj);

, python, javascript dicts ( ). .

+4

/ , , . ...

{ colorAttribute: '#' + hex }

... Object "colorAttribute".

:

var css = {};
css[colorAttribute] = '#' + hex;
$(thisClass).css(css);
+4

javascript . , .

, , , :

var obj = {};
obj[colorAttribute] = '#'+hex;
$(thisCLass).css(obj);
+3

{ colorAttribute : '#'+hex }, "colorAttribute".

, ,

var cssObject = {};
cssObject[colorAttribute] = '#'+hex;
//cssObject[otherAttribute] = 'otherValue';
$(thisCLass).css(cssObject);

, .

+2

, , :

:

var color = new Object();
color.colorAttribute = '#'+hex

$(thisCLass).css(color);
+2

All Articles