我怎样才能使这个javascript工作?

时间:2015-03-19 19:12:30

标签: javascript wordpress

我将以下JS直接放在我的WordPress博客的网站上。 如果单击按钮,它应该随机播放两个音频文件中的一个。

我的问题是:

  • JS
  • 是否有任何错误/缺失
  • 如何通过按钮启动它?
<script>
var playlist = Array();
playlist.push("http://.../wp-content/uploads/2015/03/xxx.mp3");
playlist.push("...wp-content/uploads/2015/03/10-Good-Evening.mp3");


console.log(getSong()); // Here's your song.

document.getElementById("play").addEventListener("click", playSong);


function playSong(){ 
    var audio = new Audio(getSong());
    audio.play(); 
}

function getSong() {
   return playlist[Math.floor(Math.random() * playlist.length)];
} 

</script>

2 个答案:

答案 0 :(得分:1)

看起来不错!

只需在您的javascript代码

后添加此html即可
<button id="play">Click Me</button>

答案 1 :(得分:1)

控制台显示:

Navigated to http://fuba-blog.de/randomizer/
VM83:132 Uncaught SyntaxError: Unexpected token <

导航到错误显示

     <script>
var playlist = Array();
playlist.push("http://fuba-blog.de/wp-content/uploads/2015/03/alaba-button-mp3.mp3");
playlist.push("http://fuba-blog.de/wp-content/uploads/2015/03/alaba-button-mp3.mp3");</p>
<p>console.log(getSong()); // Here's your song.</p>
<p>document.getElementById("play").addEventListener("click", playSong);</p>
<p>function playSong(){ 
    var audio = new Audio(getSong());
    audio.play(); 
}</p>
<p>function getSong() {
   return playlist[Math.floor(Math.random() * playlist.length)];
} </p>
<p></script>

您的脚本中包含HTML。

相关问题