2016-05-15 126 views
1

我试图制作一个音乐播放器,当用户点击按钮时,覆盖的图像会将图像更改为stop.png并播放歌曲。当用户再次点击它时,它会将图像更改为play.png并停止播放歌曲。音乐播放器播放全部使用相同的编号

<audio id="myAudio"> 
    <source src="http://www.w3schools.com/jsref/horse.ogg" type="audio/ogg"> 
    <source src="http://www.w3schools.com/jsref/hors.mp3" type="audio/mpeg"> 
    Your browser does not support the audio element. 
</audio> 
<script> 
function plaYer() { 
    var image = document.getElementById('myImage'); 
    var x = document.getElementById("myAudio"); 

    if (image.src.match("play")) { 
     image.src = "stop.png"; 
     x.play(); 
    } else { 
     image.src = "play.png"; 
     x.pause(); 
    } 
} 
</script> 
<button id="song" 
style="color: white; background-image: url('cover100.jpg'); border: none; outline: none; display:block; 
width:100px; 
height:100px;"> 
<img id="myImage" onclick="plaYer()" src="play.png" width="100" height="100"> 
</button> 

我的问题是,当我尝试创建2音乐播放器其他音乐播放器不工作。有人能帮我吗 ?

回答

2

ID必须是唯一的。如果你想重用你的功能,你不能硬编码它的ID。由于您使用内联事件处理程序,因此您已经可以访问图像元素。通过这些信息,再加上相应的<audio>元素到您的功能ID:

function plaYer(image, audioID) { 
    var x = document.getElementById(audioID); 
    // rest of your code ... 
} 

// HTML 

<img id="myImage" onclick="plaYer(this, 'myAudio')" ... /> 

我推荐阅读excellent articles on quirksmode.org更多地了解事件处理。