簡體   English   中英

音頻事件不會在播放事件上觸發 jQuery

[英]Audio event does not trigger jQuery on play event

我嘗試在音頻play事件上執行一個函數:

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

但是我的元素在執行這個函數時不存在,所以它沒有被選中。 相反,當我需要為動態添加的內容觸發事件時,我習慣於使用不同的語法:

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

.constant-container不變的地方。 但是這個解決方案似乎不起作用,音頻元素也沒有任何click事件。

這是bin鏈接

前 4 個音頻正確處理事件,但不是最后 4 個。

顯然,媒體事件(那些專門屬於音頻視頻的事件,playpause 、時間timeupdate等)不會被冒泡。 你可以在這個問題的答案中找到解釋。

所以使用他們的解決方案,我捕獲了play事件,

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

JS Bin 演示

事件捕獲代碼(取自其他 SO 答案):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM