Jquery Output and Play Audio Elements from Json Array in Correct Order

Jquery Output and Play Audio Elements from Json Array in Correct Order

I am having trouble with outputting audio elements from a Json array with Jquery. Here is my Json array which contains images, text and audio:

"questions": [ { // Question 1 "q": "<img height=100 width=100 src=\"js/Question1Option4.png\" />", "correct": "<p>Bag</p>", "audio": "<audio src=\" js/Question1.mp3\" ></audio>" }, { // Question 2 "q": "<img height=100 width=100 src=\"js/Question2Option2.png\" />", "correct": "<p>Eraser</p>", // no comma here "audio": "<audio src=\" js/Question2.mp3\" ></audio>" }, { // Question 3 "q": "<img height=100 width=100 src=\"js/Question3Option4.png\" />", "correct": "<p>Pencil</p>", // no comma here "audio": "<audio src=\" js/Question3.mp3\" ></audio>" }, ]


My jquery script appends the image, text and audio for each question one after another. It also appends divs with function buttons for revealing and playing the text and audio elements on click:

for ( i in questions ) { if ( questions . hasOwnProperty ( i )) { var question = questions [ i ];

var questionHTML = $ ( '<li class="question" id="question' + ( count - 1 ) + '"></li>' );

questionHTML
. append ( '<table><tr ><td class="column-1"><div class="q";><h3><br>' + count + '. ' + question . q + '</h3></div></td><td class="column-2"><div class="correct"><h3>' + count + '. ' + question . correct + question . audio + '<div input class="playSound" type="submit"><button>Play</button></div>' + ' </h3></td></tr></table>' )

The relevant stuff is in the appending of the text and audio within the "correct" div towards the end of "QuestionHTML.append" The text and audio elements are appended along with buttons to reveal and play those elements respectively.

As a result, the image and text elements are each outputted in order along with "Play" buttons for the purposes of playing the corresponding audio element.

Issue: How do I create a function for the "Play" buttons to play their respective audio elements on click?

The audio elements were correctly appended from json as shown by this function:

$ ( ".playSound" ). click ( function () {
$
( "audio" )[ 0 ]. play ();
});

But here, each "Play" button only plays the audio element that is designated in the $("audio")[X] brackets. I have tried to create functions with ".this" and ".each" but these result in each "Play" button playing every audio element at the same time.

So yeah, how do I create a general function for multiple buttons that identifies and plays the correct audio element based on its order within the json array? Any guidance or clues would be most helpful

Thanks guys