为页面上的所有音频标签添加播放按钮

我想为页面上的每个音频文件添加一个播放按钮。 因此,我在每个音频标签下添加了一个带索引类名的按钮,但现在我不知道如何继续并将click事件绑定到按钮。 也许总的来说有更优雅的方法……

   
 $( "audio" ).each(function( index ) { $( '' ).insertAfter( this ); }); $("button").on("click", playTest); 

我注意到你使用了相同值的多个id(永远不会工作),所以我删除了它们。 我使用之前的海报代码来创建按钮,但已经详细说明了如何在playTest函数中调用每个音频。 希望这可以帮助!

 $("audio").each(function(index) { $(this).attr('id','myaudio' + index); $('').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(); } } 
    

如果按钮是动态创建的,您必须委托要在其上执行的任何事件。

希望这个片段有用

 $( "audio" ).each(function( index ) { $( '' ).insertAfter(this ); }); $("body").on("click","button" ,playTest); function playTest(){ alert($(this).prop('class')) } 

的jsfiddle