2016-06-18 5 views
2

ページ上の各オーディオファイルに再生ボタンを追加したいとします。 したがって、各オーディオタグの下にインデックス付きのクラス名を持つボタンを追加しましたが、ボタンへのクリックイベントの進行方法とバインド方法はわかりません。ボタンを動的にあなたがそれを実行するすべてのイベントを委任する必要が作成されますので、 はたぶんはるかにエレガントなアプローチは、一般的な...ページ上のすべてのオーディオタグに再生ボタンを追加する

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<audio id="myaudio" src="http://www.soundjay.com//mechanical/gun-cocking-01.mp3"> 
</audio> 

<audio id="myaudio" src="http://www.soundjay.com//mechanical/gun-cocking-02.mp3"> 
</audio> 
$("audio").each(function(index) { 
    $('<button class=audioButton"' + index + '">Play Clip #' + index + '</button>').insertAfter(this); 
}); 

$("button").on("click", playTest); 

答えて

1

有用であろう

希望は私はあなたが(仕事に行くことはありません)同じ値の複数のIDを使用していた気づいたので、私はそれらを削除しました。以前のポスターのコードを使ってボタンを作成しましたが、playTest関数で各オーディオをどのように呼び出すことができるかを詳しく説明しました。お役に立てれば!

$("audio").each(function(index) { 
 
    $(this).attr('id','myaudio' + index); 
 
    $('<button id="audio' + index + '">Play Clip #' + index + '</button>').insertAfter(this); 
 
}); 
 

 
$("body").on("click", "button", playTest); 
 

 
function playTest() { 
 
    var audid = 'my'+ $(this).attr('id'); 
 
    playAudio(audid); 
 
} 
 

 
function playAudio(str) { 
 
    var currAudio = document.getElementById(str); 
 
    if (currAudio.paused) { 
 
    currAudio.play(); 
 
    } else { 
 
    currAudio.pause(); 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<audio src="http://www.soundjay.com//mechanical/gun-cocking-01.mp3"> 
 
</audio> 
 

 
<audio src="http://www.rachelgallen.com/monkey.mp3"> 
 
</audio>

+0

https://jsfiddle.net/RachGal/5gr5b38L/ –

1

にあります。このスニペットは

$("audio").each(function(index) { 
    $('<button class="audioButton' + index + '">Play Clip #' + index + '</button>').insertAfter(this); 
}); 

$("body").on("click","button" ,playTest); 
function playTest(){ 
alert($(this).prop('class')) 

} 

JSFIDDLE

+0

ただ、実際にファイルを再生するには、あなたのスニペットを使用する方法がわかりません! – Madamadam

+0

あなたはplayTest関数を書いていますか? – brk

+0

いいえ、それは問題です。あなたがそのplayTest関数をコーディングする方法を教えてくれれば、 – Madamadam

関連する問題