HTML5 音频和 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6588934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:05:43  来源:igfitidea点击:

HTML5 Audio and jQuery

jqueryhtmlaudioplayback

提问by user699242

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

我正在尝试使用按钮在 HTML5 音频标签中使用 jQuery 开始曲目,但我一直收到错误消息。

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:

当我使用 document.getElementById('audio') 时,它可以工作,但是当使用 jQuery 选择器时,我收到以下错误:

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

未捕获的类型错误:对象 [object Object] 没有方法“播放”

Thanks for any help.

谢谢你的帮助。

回答by Darin Dimitrov

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

尝试获取原生 DOM 元素,因为 jQuery.play$('#audio')选择器返回的包装数组上的方法一无所知:

song.get(0).play();

回答by Cole Garstin

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

你也可以像song.trigger('play');. 这将允许您使用$('#audio');选择器。

回答by sidonaldson

Instead of .get() just use object notation:

而不是 .get() 只是使用对象表示法:

var song = $('#audio');

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

It's less to type :)

打字少了:)