1

我想在我的网站上播放随机音轨..没有任何前进/后退控制..我使用的代码是..

<script type="text/javascript">
var a = Math.random()*2;
a=Math.floor(a);

if(a==1)
{alert(a); document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='6.ogg' type='audio/ogg'>Your browser does not support the audio element.</audio>";}
if(a==0)
{alert("hello");document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='5.ogg' type='audio/ogg'>Your browser does not support the audio element.</audio>";}

</script>

<div id="soundtrack">

</div>

但是这段代码没有播放任何东西..(警报进展顺利)我该怎么办???

4

2 回答 2

0

这就是(一个原因)为什么将 JavaScript 放在 BODY 标记的末尾是个好主意。正如 Mikhail 所说,脚本运行时尚未加载 DIV 标签。HTML 页面按照您输入的顺序进行处理(除非您使用函数和事件处理程序)。一个简单的解决方法是将 DIV 移动到页面顶部,如下所示:

<html>
<body>
<div id="soundtrack"></div>

<script type="text/javascript">
var a = Math.random()*2;
a=Math.floor(a);

if(a==1)
{alert(a); document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='6.ogg' type='audio/ogg'>Your browser does not support the audio element.</audio>";}
if(a==0)
{alert("hello");document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='5.ogg' type='audio/ogg'>Your browser does not support the audio element.</audio>";}

</script>
</body>
</html>
于 2013-01-18T08:05:46.207 回答
0

实际上,当您运行脚本时,div 并未初始化。你需要把它放在 onload hadler 中。这个例子对我有用:

<script type="text/javascript">
function play()
{
    var a = Math.random()*2;
    a=Math.floor(a);

    if(a==1)
    {
        alert(a); 
        document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='1.mp3' type='audio/ogg'>Your browser does not support the audio element.</audio>";
    }
    if(a==0)
    {
        alert(document.getElementById('soundtrack'))
        document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='0.mp3' type='audio/ogg'>Your browser does not support the audio element.</audio>";
    }
}
</script>
<body onload="play()">;
<div id="soundtrack">

</div>
</body>
于 2013-01-18T07:51:19.733 回答