[英]Convert string to JS object
I know its a repeated questions but I cannot figure out how to do in my case. 我知道这是一个重复的问题,但是我无法弄清楚该怎么办。 I want to play audio using JS Buzz library.
我想使用JS Buzz库播放音频。 Please check following
请检查以下
var pg1 = new buzz.sound("oimages/music/as.mp3");
var pg2 = new buzz.sound("oimages/music/zx.mp3");
var pg3 = new buzz.sound("oimages/music/as.mp3");
On a certain event I want to play this audio. 在某些事件中,我想播放此音频。 here 1, 2 and 3 are page numbers.
这里的1、2和3是页码。 Please check following
请检查以下
$("#flipbook").bind("turned", function (event, page, view) {;
bog ='pg'+page; // page is the number of page here
window.bog.play(); //error
});
It gives me following error 它给我以下错误
Uncaught TypeError: window.bog.play is not a function
未捕获的TypeError:window.bog.play不是函数
Please guide. 请指导。
Simple mistake. 简单的错误。 You're trying to reference the variable incorrectly.
您试图错误地引用变量。
bog
isn't the name, but it contains the name... bog
不是名字,但其中包含名字...
$("#flipbook").bind("turned", function (event, page, view) {;
bog ='pg'+page; // page is the number of page here
window[bog]play(); //error
});
This assumes that the pg1..3
variables have global scope. 假设
pg1..3
变量具有全局作用域。 If they don't then change the declarations to... 如果他们不这样做,则将声明更改为...
window.pg1 = new buzz.sound("oimages/music/as.mp3");
etc.. 等等..
Because bog ='pg'+page;
因为
bog ='pg'+page;
is a string, not a reference to the sound file. 是一个字符串,而不是对声音文件的引用。
You need to reference the sound assuming they are in global scope you can use bracket notation 您需要引用声音,前提是它们在全局范围内,您可以使用方括号表示法
var bog = window['pg'+page];
Evaluating would do the trick: 评估将达到目的:
$("#flipbook").bind("turned", function (event, page, view) {;
bog ='pg'+page;
eval('window.' + bog + '.play()');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.