admin管理员组

文章数量:1405983

So i have been doing some JavaScript and is currently learning jQuery. Time to time i get a bit confused by how jQuery does things pared to JS.

Got an HTML audio tag that looks something like this:

<audio id="audio" src="audio.mp3"></audio>

With JS i simply play it with:

document.getElementById('audio').play();

So i figured, doing the same with jQuery would just be:

$('#audio').play();

That doesn't work, instead i have to write it like this:

$('#audio')[0].play();

Can anyone explain this to me?

Thanks.

So i have been doing some JavaScript and is currently learning jQuery. Time to time i get a bit confused by how jQuery does things pared to JS.

Got an HTML audio tag that looks something like this:

<audio id="audio" src="audio.mp3"></audio>

With JS i simply play it with:

document.getElementById('audio').play();

So i figured, doing the same with jQuery would just be:

$('#audio').play();

That doesn't work, instead i have to write it like this:

$('#audio')[0].play();

Can anyone explain this to me?

Thanks.

Share Improve this question asked Jul 22, 2015 at 13:21 qua1ityqua1ity 6232 gold badges9 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

The following code :

$('#audio').play();

gives you back an array of elements that match the query selector wrapped with jQuery functions, this is how jQuery works, in your case it will give an array with one element .

the .play function is not a jQuery function and works directly on the html element, thus, you need to go to the first element in the jQuery array and then use the .play function

本文标签: javascriptjQuery play AudioStack Overflow