gpt4 book ai didi

javascript - “Ended”HTML5 事件未绑定(bind)到绑定(bind)后创建的元素上

转载 作者:行者123 更新时间:2023-12-03 11:48:42 25 4
gpt4 key购买 nike

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

<!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>

实际上事件只绑定(bind)在第一个元素上,附加到事件中的第二个元素没有绑定(bind)

最佳答案

尝试一下:不要尝试更改音频的 src,而是绑定(bind)事件,并将此脚本包装在 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()
});
});

关于javascript - “Ended”HTML5 事件未绑定(bind)到绑定(bind)后创建的元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25931352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com