说明(2017.3.29):
1. 在调试工具console里输入var v = document.createElement("audio"),然后再source的watch里输入v回车,就能看到audio的所有事件,本次使用的是onended事件。
2. json不能直接遍历获得索引,只能通过for循环获取个数,再用for循环遍历。所以最好用数组存放歌名。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <audio id="music" src="Taylor Swift - Love Story.mp3" controls="controls" autoplay="autoplay">浏览器不支持</audio> 9 10 11 </body> 12 <script type="text/javascript"> 13 var songs = { 14 1:"Taylor Swift - Love Story.mp3", 15 2:"unity.mp3", 16 3:"alone.mp3", 17 4:"chinese-supermarkets-stop-selling-brazilian-meat-over-food-safety-scandal.mp3" 18 }; 19 // var music = document.getElementById("music"); 20 // var num = (function(){ 21 // var num = 0; 22 // for(var i in songs){ 23 // num ++ 24 // } 25 // return num; 26 // })(); 27 // var i = 1; 28 // setInterval(function(){ 29 // if(i < num){ 30 // if(music.ended){ 31 // music.src = songs[i+1]; 32 // i++; 33 // } 34 // }else{ 35 // i = 0; 36 // } 37 38 // },1000); 39 40 var num = (function(){ 41 var num = 0; 42 for(var i in songs){ 43 num ++ 44 } 45 return num; 46 })(); 47 var i = 1; 48 music.onended = function(){ 49 if(i < num){ 50 music.src = songs[i+1]; 51 i++; 52 }else{ 53 i = 0; 54 music.src = songs[i+1]; 55 i++; 56 } 57 }; 58 59 60 </script> 61 </html>