'已结束'HTML5事件未绑定到绑定后创建的元素上

'Ended' HTML5 event is not binded on elements created after binding

本文关键字:绑定 创建 元素 结束 HTML5 事件      更新时间:2023-09-26

我正在开发一些在线mp3播放列表解决方案,遇到了一些奇怪的问题。我想在所有存在或将来将存在的音频元素上绑定"已结束"事件。该策略是在现有元素播放结束后添加新的音频元素。代码如下:

<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<div id='audio_content'>
<audio class='playable' controls >
  <source  rel='1' src="/files/1.mp3" type="audio/mpeg"/>
</audio>
</div>
<script type="text/javascript">

$(".playable").on('ended',function(){
  var id = $(this).find('source').attr('rel');
  $("#audio_content").append("<audio class='playable' controls ><source rel='"+(parseInt(id)+1)+"' src='/files/"+(parseInt(id)+1)+".mp3' type='audio/mpeg'/></audio>");
  $("[rel="+(parseInt(id)+1)+"]").closest('audio')[0].play()
});
</script>
</body>
</html>

事实上,事件只绑定在第一个元素上,附加在事件内部的第二个元素没有绑定

试试这个:不要绑定事件,而是尝试更改音频的src,也要将这个脚本封装在document.ready

$(document).ready(function(){
    $(".playable").on('ended',function(){
      var source = $(this).find('source');
      var id = $(source).attr('rel');
      var newId = parseInt(id)+1;
      //update rel and src
      $(source).attr('rel',newId);
      $(source).attr('src',"/files/"+newId+".mp3");
      $(this)[0].load()
      $(this)[0].play()
    });
});