Img / Audio更改为document.getElementByID(“...”)。src = x +“。png”;不会工作

时间:2014-01-22 11:03:13

标签: javascript image onclick getelementbyid

我无法弄清楚它为什么不起作用。由于它没有什么特别之处,我在网上搜索 - 而且我在这里找到的只是没有变量的教程或者有太具体问题的问题。

有人可以指导我吗?

<html>
<head>
<title>Test</title>
<script type="text/javascript">

function changeaudio(x);
{

  document.getElementById("audioplayer").src=x+".mp3";
  document.getElementById("image").src=x+".png";
}

</script>
</head>
<body>
<center>
<img id="image" src="1.png">
<audio id="audioplayer" src="1.mp3" controls autoplay loop>
Your browser does not support the audio element.
</audio> 
<br>

<input type="button" id="play" value="Play 1" onclick='changeaudio(1)"' />
<input type="button" id="play2" value="Play 2" onclick='changeaudio(2)"' />
<input type="button" id="play3" value="Play 3" onclick='changeaudio(3)"' />
</center>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

在功能定义后移除;function changeaudio(x);应变为:function changeaudio(x)

此外,您的onclick语法错误:onclick='changeaudio(1)"'应该是:onclick="changeaudio(1)"

您的最终代码应如下所示:

<html>
    <head>
        <title>Test</title>
        <script type="text/javascript">
        function changeaudio(x)
        {
            document.getElementById("audioplayer").src=x+".mp3";
            document.getElementById("image").src=x+".png";
        }
        </script>
    </head>
    <body>
        <center>
            <img id="image" src="1.png" />
            <audio id="audioplayer" src="1.mp3" controls autoplay loop>
                Your browser does not support the audio element.
            </audio> 
            <br />
            <input type="button" id="play" value="Play 1" onclick="changeaudio(1)" />
            <input type="button" id="play2" value="Play 2" onclick="changeaudio(2)" />
            <input type="button" id="play3" value="Play 3" onclick="changeaudio(3)" />
        </center>
    </body>
</html>

jsFiddle Demo

答案 1 :(得分:0)

用于jquery方法:

$(function(){
    $('.play').each(function() {
       var mp3 = $(this).attr("id"); 
        $(this).click(function(){
           $('#audioplayer').attr("src", mp3+".mp3"); 
           $('#image').attr("src", mp3+".png"); 
        });
    });

});

 <center>
            <img id="image" src="1.png" />
            <audio id="audioplayer" src="1.mp3" controls autoplay loop>
            </audio> 
            <br />
            <input type="button" class="play" id="1" value="Play 1" />
            <input type="button" class="play" id="2" value="Play 2"  />
            <input type="button" class="play" id="3" value="Play 3" />
        </center>

<强> jsFIDDLE DEMO