音频事件不会在播放事件中触发jquery [英] Audio event does not trigger jquery on play event

查看:335
本文介绍了音频事件不会在播放事件中触发jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试执行一个音频播放功能事件:

I try to execute a function on an audio play event :

jQuery('audio').on('play', function () { /* ... */ });

但是,在执行此函数时,我的元素不存在,因此未选中该元素。相反,当我需要触发动态添加内容的事件时,我习惯使用不同的语法:

But my element is not present at the time this function is executed, so it's not selected. Instead I have the habit to use a different syntax when I need to trigger event for dynamic added content :

jQuery('.constant-container').on('play', 'audio', function () {
    /* ... */ 
});

哪里 .constant-container 不更改。
但是这个解决方案似乎不起作用,音频元素也没有得到任何点击事件。

这是一个链接到bin

前4个音频句柄正确的事件,但不是最后4个。

The first 4 audio handle correctly the event, but not the 4 last.

推荐答案

显然,媒体事件(特别属于 视频的媒体事件,如播放 pause timeupdate 等)不要冒泡。您可以在此问题的答案中找到解释。

Apparently media events( those specifically belonging to audio or video like play, pause, timeupdate, etc) do not get bubbled. you can find the explanation for that in the answer to this question.

所以使用他们的解决方案,我捕获了 play 事件,

So using their solution, I captured the play event,

jQuery.createEventCapturing(['play']);  
jQuery('body').on('play', 'audio', function(){... // now this would work.



JS Bin演示



事件捕获代码(取自其他SO答案):

JS Bin demo

the code for event capturing( taken from the other SO answer):

    jQuery.createEventCapturing = (function () {
        var special = jQuery.event.special;
        return function (names) {
            if (!document.addEventListener) {
                return;
            }
            if (typeof names == 'string') {
                names = [names];
            }
            jQuery.each(names, function (i, name) {
                var handler = function (e) {
                    e = jQuery.event.fix(e);

                    return jQuery.event.dispatch.call(this, e);
                };
                special[name] = special[name] || {};
                if (special[name].setup || special[name].teardown) {
                    return;
                }
                jQuery.extend(special[name], {
                    setup: function () {
                        this.addEventListener(name, handler, true);
                    },
                    teardown: function () {
                        this.removeEventListener(name, handler, true);
                    }
                });
            });
        };
    })();

这篇关于音频事件不会在播放事件中触发jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆