按下图像后重新加载Javascript(功能)

时间:2015-03-14 11:21:03

标签: javascript html5

我正在制作一个从变量列表中选择随机歌曲的mp3播放器。有代码:

<b>Title</b>: <span id='songTitle'></span><br>
<b>Album</b>: <span id='songAlbum'></span><br>

<audio class="audio-element" controls="true" preload="none">

<!-- Adding audio sources -->

            <source src="mp3file.mp3" type="audio/mpeg" />
<br>
<b>Your outdated browser does not support HTML5. <br>
Get Mozilla Firefox <a href="https://www.mozilla.org/pl/firefox/new/"> >HERE< </a></b>

</audio>

<script>
var songs =
[
    { filename: "title1.mp3", title: "title1", album: "Album1" },
    { filename: "title2.mp3", title: "title2", album: "Album2" },
    // add more songs here...
];

var randomIndex = Math.floor(Math.random() * songs.length);
var song = songs[randomIndex];
document.querySelector("source").src = song.filename;
document.getElementById("songTitle").textContent = song.title;
document.getElementById("songAlbum").textContent = song.album;
</script>

是否有选项,在按下指定的图像后,代码将刷新(它将再次选择一首歌并显示其细节)而不刷新整个页面?

1 个答案:

答案 0 :(得分:1)

将要刷新的代码放入函数中。

<script> 
var songs = ...
function f(){
    var randomIndex = Math.floor(Math.random() * songs.length);
    var song = songs[randomIndex]; document.querySelector("source").src = song.filename;
    document.getElementById("songTitle").textContent = song.title;
    document.getElementById("songAlbum").textContent = song.album;
}
</script>

然后将该函数设置为onclick的callback。就这样:

<img ... onclick="f();" ... />