开发者

Using square brackets to concatenate things in Javascript?

Anyone know why this isn't working?

$('#screen').css({
  'background-image': [bg_num == 1 ? 'josh' : 'jessi'] + '_background.jpg',
  'background-color': 'red'
 });

The background color is getting set, but the image is not.

I've not really had much practice using squar开发者_如何转开发e brackets in Javascript to get this kind of thing done. Anyone have tips if I'm doing something way wrong? Or no of a nice explanation of their use?

EDIT: And just to be clear, the check itself is actually happening, because if I do the same thing in a console.log() is outputs "josh_background.jpg" just fine. It's just not taking in this css setting function.


EDIT:

What you were doing was creating an Array literal with the value 'josh' or 'jessi', then concatenating '_background.jpg' onto it, so it technically would work.

The issue is that you're missing the 'url()' part of the background-image value.

'background-image': 'url(' + (bg_num == 1 ? 'josh' : 'jessi') + '_background.jpg)',

...but you should still use the () for grouping instead of constructing an Array.


Original answer:

Use parentheses for grouping instead of square brackets:

'background-image': (bg_num == 1 ? 'josh' : 'jessi') + '_background.jpg',

The only use you'll have for square brackets in javascript will be for getting/setting a property on an object, or for creating an Array literal:

var arr = []; // An Array literal

arr[10] = 'someArrValue'; // set index 10


var obj = {};  // A plain object literal

obj['prop'] = 'someObjValue';  // set the "prop" property

var key = 'prop2';

obj[key] = 'someOtherObjValue'; // set the property referenced in the "key" variable

...oh, they have use in regular expression syntax of course...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜