简体   繁体   English

使用方括号连接Javascript中的内容?

[英]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 square brackets in Javascript to get this kind of thing done. 我实际上并没有太多练习在Javascript中使用方括号来完成这种事情。 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. 编辑:而且要清楚,检查本身实际上是在进行,因为如果我在console.log()中做同样的事情,则输出“ josh_background.jpg”就好了。 It's just not taking in this css setting function. 只是不使用此CSS设置功能。

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. 你这样做是创建一个数组文本与价值'josh''jessi' ,然后串联'_background.jpg'到它,所以它在技术上是可行的。

The issue is that you're missing the 'url()' part of the background-image value. 问题是您缺少background-image值的'url()'部分。

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

...but you should still use the () for grouping instead of constructing an Array. ...但是您仍应使用()进行分组,而不是构造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: 在javascript中,方括号的唯一用途是用于获取/设置对象的属性或创建Array文字:

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... ...哦,他们当然在正则表达式语法中使用了...

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

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