如何使用Javascript来选择按钮的价值音频文件 [英] How do I use Javascript to Select Audio File from Button Value
问题描述
所以,我有按钮阵列所有不同的价值观和我希望他们播放的歌曲与点击时的数值。所有文件的编号,即1.MP3,2.MP3,3.MP3等。
So I have an array of buttons all with different values and I want them play the song with it's number value, when clicked. All of the files are numbered, i.e. 1.mp3, 2.mp3, 3.mp3, etc.
有没有这样做没有大量重复的Javascript code为每首歌曲的一种方式。
Is there a way of doing it without a lot of repeating Javascript code for each song.
下面是我的HTML:
<audio id="player">
<source id="sourceMp3" src="" type="audio/mp3">
Your browser does not support the audio element.
</audio>
<button onclick="loadSong()" value="1">1</button>
<button onclick="loadSong()" value="2">2</button>
<button onclick="loadSong()" value="3">3</button>
<button onclick="loadSong()" value="4">4</button>
<button onclick="loadSong()" value="5">5</button>
下面是我的JavaScript:
Here is my JavaScript:
function loadSong(){
var player=document.getElementById('player');
var songNo = document.getElementByTagName('button').value;
var sourceMp3=document.getElementById('player');
sourceMp3.src='songs/' + songNo + '.mp3;
player.load();
player.play();
}
任何建议将是极大的AP preciated。
Any suggestions would be greatly appreciated.
推荐答案
您在JS调用部分应该是:
Your call in the JS portion should be:
var sourceMp3=document.getElementById('sourceMp3');
然后
sourceMp3.src='songs/' + songNo + 'mp3';
应该工作。
注意,你应该选择的&lt的SRC;源&GT; - 标记,而不是在&lt;音频&GT; -tag
Notice, you should pick the 'src' of the <source>-tag, not the <audio>-tag
另外,我想补充一个函数调用的按钮: - 然后定义函数如下:功能LoadSong来(songNo)...
also, I would add a function-call with the buttons: - and then define your function like this: function loadSong(songNo)...
所以,你的code可能是这样的:
So, your code could look like this:
<audio id="player">
<source id="sourceMp3" src="" type="audio/mp3">
Your browser does not support the audio element.
</audio>
<button onclick="loadSong(1)">1</button>
<button onclick="loadSong(2)">2</button>
<button onclick="loadSong(3)">3</button>
<button onclick="loadSong(4)">4</button>
<button onclick="loadSong(5)">5</button>
和JS的:
function loadSong(songNo) {
var player=document.getElementById('player');
var sourceMp3=document.getElementById('sourceMp3');
sourceMp3.src='songs/' + songNo + '.mp3';
player.load();
player.play();
这篇关于如何使用Javascript来选择按钮的价值音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!