在 Javascript 中使用方括号来连接事物?
有人知道为什么这不起作用吗?
$('#screen').css({
'background-image': [bg_num == 1 ? 'josh' : 'jessi'] + '_background.jpg',
'background-color': 'red'
});
背景颜色已设置,但图像尚未设置。
我还没有太多练习在 Javascript 中使用方括号来完成这种事情。如果我做错了什么,有人有提示吗?或者没有一个很好的解释它们的用途?
编辑:为了清楚起见,检查本身实际上正在发生,因为如果我在 console.log() 中执行相同的操作,则输出“josh_background.jpg”就好了。只是没有采用这个css设置功能。
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. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:
您所做的是创建一个值为
'josh'
或'jessi'
的数组文字,然后连接'_background .jpg'
到它上面,所以从技术上讲它是可行的。问题是您缺少
background-image
值的'url()'
部分。...但是您仍然应该使用
()
进行分组而不是构造数组。原始答案:
使用圆括号代替方括号进行分组:
在 JavaScript 中方括号的唯一用途是获取/设置对象的属性,或者创建数组文字:
...哦,它们当然可以在正则表达式语法中使用...
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 thebackground-image
value....but you should still use the
()
for grouping instead of constructing an Array.Original answer:
Use parentheses for grouping instead of square brackets:
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:
...oh, they have use in regular expression syntax of course...