2016-11-25 86 views
0

我目前正在为教育目的制作一个页面。现在我正在制作一个包含多个按钮的页面,这些按钮包含当你点击它们时会播放音乐的功能。现在我需要其中的10个在彼此之下。但我有10个不同的声音片段。如果我把10个不同的脚本放在eachother下面,那会让我感到非常混乱,我想知道是否可以将这些脚本放在另一个文件中。还是有更简单的方法来做到这一点?我有这个想法,这可以更容易。我的页面需要使用多个脚本的外部脚本页面

这是我使用的脚本和html。

<script> 

     function playMusic(){ 
      var audio = document.getElementById("geluidsopname"); 
      audio.play(); 
     } 
    </script> 

     <button id="voortgang-button" onclick="playMusic()" value="button">  
     <img id="afspeelbutton" src ="../../../image/afspeelbutton1.png">     </img>Ik heet Marie.  
     <audio id="geluidsopname" src="../../../voice-recording/Marie.mp3"></audio> 
    </button> 
+0

你的意思是这样的:http://www.w3schools.com/tags/tag_script.asp –

+0

在任何情况下,你可以概括你的脚本采取一个参数,以便你可以做这样的事情:onclick =“playMusic ('my_audio_id')“,那么只需要1个脚本副本。 –

+0

@vladimirM听起来很有趣!你能解释一下吗?不能我也使用onclick =“playMusic(我的来源)”,所以它呼吁脚本,然后脚本将获得我的onclick音乐的来源?你是这个意思吗?当谈到java时我很新,有没有可能帮助我呢? –

回答

0

你不一定需要每一个元素的独特id分配,可以通过不同的方式访问它们。例如,看看document.querySelector

在HTML事件属性中调用JS函数是罚款,但不推荐。直接在你的JS代码上注册一个事件要干净得多。

您可能希望在body的关闭之前放置一个脚本,或最终将其放入head并在DOMContentLoaded上执行。

<button class="myBtn" id="button1"> 
    <img src="url"> 
    <audio> 
    <source src="url" type="audio/mpeg"> 
    Your browser does not support the audio feature. 
    </audio> 
</button> 

<script type="text/javascript"> 
    for (var aud in document.querySelectorAll('.myBtn')) { 
     aud.addEventListener('click', function() { 
     aud.querySelector('audio').play(); 
     }, false); 
    } 
</script> 

当然,你可以只在controls属性添加到audio元素,并有相关的浏览器处理的音频控件的所有事件:

<button class="myBtn"> 
    <img src="url"> 
    <audio controls> 
    <source src="url" type="audio/mpeg"> 
    Your browser does not support the audio feature. 
    </audio> 
</button> 
0

下面是代码的plunker。我已经修改了演示的html结构。仍然有这样的想法:你的脚本使用参数。

// Code goes here 

    function playMusic (target){ 
     console.log(target.getAttribute("target_audio")) 
     var audio = document.getElementById(target.getAttribute("target_audio")); 
     audio.play(); 
    } 

和HTML:

<!DOCTYPE html> 
<html> 

    <head> 
    <link rel="stylesheet" href="style.css"> 
    <script src="script.js"></script> 
    </head> 

    <body> 
    <input type="button" id="voortgang-button" target_audio="geluidsopname" onclick="playMusic(this)" value="button"> 
    <img id="afspeelbutton" src ="../../../image/afspeelbutton1.png">Ik heet Marie.  
    <audio id="geluidsopname" src="../../../voice-recording/Marie.mp3"></audio> 

    </body> 

</html> 

如果你喜欢,你可以通过ID作为一个字符串,该处理方法。那么你甚至不需要获取属性的值。

相关问题