我有问题在下面的代码中添加JS变量“vpath”:
var vpath = myarr[0];
jwplayer("player").setup({
flashplayer: "player.swf",
config:"config.xml",
autostart: false,
allowscriptaccess: "always",
height: 500,
width: 625,
plugins: {
'http//www.test.com/'+ vpath +'/proxy.swf': {link:"http://www.test.com/link.php"},
'http//www.test.com/image.swf': {link:"http://www.test.com/image.jpg"}
}
});
存在SyntaxError:missing:属性id之后。现在有人怎么做? 谢谢。
答案 0 :(得分:2)
您不能在object literals内的属性名称中使用变量(精确的语法和语义在§11.1.5中指定)。解决方案是首先使用任何静态属性定义对象,然后向对象添加任何动态属性。
在您的情况下,我建议您单独创建plugins
对象,如下所示:
var vpath = myarr[0];
var plugins = {};
plugins['http//www.test.com/image.swf'] = {link:"http://www.test.com/image.jpg"}
plugins['http//www.test.com/'+ vpath +'/proxy.swf'] = {link:"http://www.test.com/link.php"};
jwplayer("player").setup({
flashplayer: "player.swf",
config:"config.xml",
autostart: false,
allowscriptaccess: "always",
height: 500,
width: 625,
plugins: plugins
});
另一种在某些情况下可能有用的替代方法是使用IIFE:
var vpath = myarr[0];
jwplayer("player").setup({
flashplayer: "player.swf",
config:"config.xml",
autostart: false,
allowscriptaccess: "always",
height: 500,
width: 625,
plugins: (function() {
var obj = {};
obj['http//www.test.com/image.swf'] = {link:"http://www.test.com/image.jpg"}
obj['http//www.test.com/'+ vpath +'/proxy.swf'] = {link:"http://www.test.com/link.php"};
})()
});