<audio id="audio" src="waring.wav" preload="auto" controls loop></audio>
$('#audio').play();
报错原因:play()方法属于DOM对象方法,$('#audio')为jquery对象
解决办法:将jquery对象转换为DOM对象
首先打印jquery对象$('#audio')
两种转换方式将一个jQuery对象转换成DOM对象:[index]和.get(index);�0�2
(1)jQuery对象是一个数据对象,可以通过[index]的方法,来得到相应的DOM对象。�0�2
如:var audio =$('#audio') ; //jQuery对象�0�2
var au=audio�0�2[0]; //DOM对象�0�2
(2)jQuery本身提供,通过.get(index)方法,得到相应的DOM对象�0�2
如:var audio =$('#audio')�0�2;//jQuery对象�0�2
var au=audio.get(0); //DOM对象�0�2
==============================
-------------------------------------------------
=============================
2down voteaccepted
Example solution based on your question:
var myAudio = $("#song")[0];
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="song" src="https://ia801009.us.archive.org/4/items/BeatlesGreatestHits/02%20With%20a%20Little%20Help%20From%20My%20Friends.mp3"></audio>
<img onclick="togglePlay()" src="https://pmcdeadline2.files.wordpress.com/2014/06/the-beatles-1__140613232022.jpg" width="100%">