HTML5 Audio and jQuery

寵の児 提交于 2019-12-18 12:14:31

问题


I am trying to use a button to start a track in an HTML5 audio tag using jQuery, but I keep getting an error.

var song = $('#audio');

$('#play').click(function() {
song.play();
});

When I use document.getElementById('audio'), it works, but when using the jQuery selector I get the following error:

Uncaught TypeError: Object [object Object] has no method 'play'

Thanks for any help.


回答1:


Try getting the native DOM element as jQuery knows nothing about .play method on the wrapped array returned by the $('#audio') selector:

song.get(0).play();



回答2:


You can also write it like song.trigger('play');. That will allow you to use the $('#audio'); selector.




回答3:


Instead of .get() just use object notation:

var song = $('#audio');

$('#play').click(function() {
    song[0].play();
});

It's less to type :)



来源:https://stackoverflow.com/questions/6588934/html5-audio-and-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!