Audio event does not trigger jquery on play event

偶尔善良 提交于 2019-12-23 17:38:49

问题


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 () {
    /* ... */ 
});

Where the .constant-container does not change. But this solution does not seems to work, the audio element does not get any click event either.

Here is a link to the bin.

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


回答1:


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.

So using their solution, I captured the play event,

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

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);
                    }
                });
            });
        };
    })();


来源:https://stackoverflow.com/questions/33594647/audio-event-does-not-trigger-jquery-on-play-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!