点击js播放声音

时间:2016-06-10 11:00:36

标签: javascript html

播放音乐时遇到问题。它没玩。我想点击按钮播放音乐。

<script>
  $(document).ready(function() {
    $('.button').submit(function() {
      var audio = document.getElementById('audioFile');
      audio.play();
    });
  });
</script>
</head>

<body>
  <audio id="audioFile">
    <source src="font/sound.mp3" type="audio/mpeg">
  </audio>
  <div class="inputMessage">

    <form method="POST" action="/index.php">
      <textarea class="chatMessage" name="text" placeholder="Текст сообщения"></textarea>
      <br>
      <input class="button" type="submit" name="enter" value="Отправить">
      <input type="reset" value="Очистить">
    </form>
  </div>
</body>

1 个答案:

答案 0 :(得分:2)

首先:表单上存在.submit()方法,而不是输入。您可以改用.click()方法。 第二件事:当您单击按钮时,表单将被发送,页面重定向到/index.php。要使播放声音成为可能,您必须保持同一页面(请求仍然可以异步发送)。以下是阻止加载新页面的方法:

$('.button').click(function(ev) { // jQuery passes the event as a parameter
  var audio = document.getElementById('audioFile');
  audio.play();
  ev.preventDefault(); // and we prevent the form from being sent
});

看一下demo:https://jsfiddle.net/s48jcrvc/1/

相关问题