从 jquery 中的动态内容中捕获所有音频结束事件

ppe*_*rin 5 javascript audio jquery html5-audio

我见过类似的问题 - 但不能解决我的问题!

我的页面上有音频,当一个结束时,我希望下一个开始,但我什至无法触发结束...

我把代码剪成这样:

function DaisyChainAudio() {
    $().on('ended', 'audio','' ,function () {
        alert('done');
    });
}
Run Code Online (Sandbox Code Playgroud)

这是从我的页面/代码中调用的(并被执行,设置断点表明了这一点)。

据我了解,这应该在文档级别设置处理程序,因此任何来自任何“音频”标签的“结束”事件(即使是动态添加的)都应该被捕获并向我显示警报......

但它永远不会着火。

编辑

到目前为止,从 Ça?atay Gürtürk 的建议中借用了一些……

function DaisyChainAudio() {
        $(function () {
        $('audio').on('ended', function (e) {
            $(e.target).load();
            var next = $(e.target).nextAll('audio');
            if (!next.length) next = $(e.target).parent().nextAll().find('audio');
            if (!next.length) next = $(e.target).parent().parent().nextAll().find('audio');
            if (next.length) $(next[0]).trigger('play');
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

我仍然想在文档级别设置它,所以我不需要担心在添加动态元素时添加它......

Çağ*_*ürk 3

尝试这个:

$('audio').on('ended', function (e) {
        alert('done');
        var endedTag=e.target; //this gives the ended audio, so you can find the next one and play it.
});
Run Code Online (Sandbox Code Playgroud)

请注意,当您动态创建新音频时,您应该分配事件。一个快速而肮脏的解决方案是:

function bindEvents(){
$('audio').off('ended').on('ended', function (e) {
            alert('done');
            var endedTag=e.target; //this gives the ended audio, so you can find the next one and play it.
    });
}
Run Code Online (Sandbox Code Playgroud)

并在创建/删除音频元素时运行bindEvents。