[英]Creating a function to create a function from list of variables in Javascript
Apologies if the title is off, I can't possibly think of how to word it. 如果标题不对,我深表歉意,我想不出该怎么写。
I am making a chrome web app and It is a sound board of sorts. 我正在制作一个chrome网络应用程序,这是一种声音板。 Right now to define the audio and listen to a button click I have been doing it like this 现在定义音频并听一个按钮的点击我一直在这样做
//Variables for creating audio loads//
var heyboosong = new Audio();
var ricksong = new Audio();
var rapgod = new Audio();
//stopfunction has a button on the html that goes and will pause the sound playing. right now it's a list of every sound. I need to change it to just pause anything that plays//
function stopmusic() {
heyboosong.pause();
ricksong.pause();
rapgod.pause();
//audio functions to listen to the buttons and make sure they are clicked, if so then wohoo sound//
function myboo() {
heyboosong.src = "mp3/myboo.mp3";
heyboosong.play();
}
document.getElementById('myboobutton').addEventListener('click', myboo);
function rickplay() {
ricksong.src = "mp3/rick.mp3";
ricksong.play();
}
document.getElementById('rickbutton').addEventListener('click', rickplay);
function rapgodplay() {
rapgod.src = "mp3/rapgod.mp3";
rapgod.play();
}
Now this works all fine and dandy but It's a pain in the but. 现在,这一切都很好而且很花哨,但是却很痛苦。 I have over 100 different sounds, not just these three listed. 我有100多种不同的声音,不仅列出了这三种声音。 So I have to type everything out each time. 所以我必须每次都输入所有内容。 Is there anyway I could condense this, with either Jquery or some other method? 无论如何,我可以用Jquery或其他方法来简化它吗?
I don't know if it will work but it will give you some ideas. 我不知道它是否会起作用,但是会给您一些想法。 If you can store the song title in the variable, I think it will work. 如果您可以将歌曲标题存储在变量中,我认为它将起作用。
var mySong = new Audio();
function stopmusic() {
mySong.pause();
}
function getSong(title) {
mySong.src = "mp3/"+ title +".mp3";
mySong.play();
}
document.getElementById(title+'button').addEventListener('click', title);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.