【问题标题】:Use of reference to calling object (this) using HTML5 audio and jQuery使用 HTML5 音频和 jQuery 对调用对象 (this) 的引用
【发布时间】:2012-03-10 20:53:50
【问题描述】:

我正在创建自己的能够处理播放列表的 HTML5 音频播放器。我创建了一个自定义 myPlaylist 对象,其中包含所有 play()pause()stop() 和其他需要的功能。这一切正常,但此外,我需要知道音频文件何时结束才能自动开始播放下一个。

这是我正在使用的代码的相关部分:

function myPlaylist(){

    var player = document.createElement('audio');
    var audio = $(player).get(0);

    this.next = function next(){
        // Picks next song in the playlist and plays it
        ...
    };

    $(audio).bind('ended', function() {
        alert("Song is finished!");
        // Here I want to call to my next() function
    });
}

我无法弄清楚该怎么做。我已经尝试了几种组合,例如$(this).next(),这似乎是最合理的并且实际上显示了警报,但随后什么都不做¿?,还有this.next(),它也显示警报但随后显示错误,因为this指 HTML5 音频元素,它没有next() 函数。

我也尝试过另一种方法,使用

audio.onended = function(){
    alert("Song is finished!");
    $(this).next();
}; 

但那些甚至不会触发警报。 audio.ended 也不起作用。

所以,我现在基本上一无所知,有人知道我做错了什么吗?提前致谢。

哦,我已经在 Mac OS X 的最新版 Google Chrome 和 Safari 中测试了所有这些。


编辑按照HTML5 audio playlist - how to play a second audio file after the first has ended?中给出的建议,我也尝试了以下代码

player.addEventListener("ended", function() {
    alert("Song is finished!");
    $(this).next();
});

player.addEventListener("ended", next);

虽然第一个能正确显示警报,但它们都不起作用。


EDIT 2 使用搜索我遇到了this question,这可能也与我的问题有关,所以为了摆脱任何可能的麻烦,参考this ,我添加了一个引用对象本身的新变量,所以现在我基本上正在使用:

function myPlaylist(){

    var player = document.createElement('audio');
    var audio = $(player).get(0);
    var me = $(this);

    this.next = function next(){
        // Picks next song in the playlist and plays it
        ...
    };

    $(audio).bind('ended', function() {
        alert("Song is finished!");
        me.next();
    });
}

然后我收到一条错误消息,指出该对象没有方法 next()

我不知道我还能尝试什么...任何额外的信息将不胜感激,谢谢!

【问题讨论】:

  • Chrome 和 Safari 中的事件名称通常不是以 on 开头(如在 audio.onended 中),在我看来更像 IE。您是否为第二个示例尝试过 audio.ended?
  • 是的,我也尝试过,结果相同,但未显示警报。但我不知道事件名称取决于浏览器。感谢您的提示。

标签: javascript jquery html html5-audio


【解决方案1】:

有一个 HTML5 播放列表示例处理 ended 事件 here,如果有帮助?

在您的事件处理程序中您引用this,但在此上下文中this 指的是捕获事件的DOM 元素,即您的audio 元素.. 试试这个:

function myPlaylist(){

    var self = this;
    var player = document.createElement('audio');

    this.next = function (){
        // Picks next song in the playlist and plays it
        ...
    };

    player.addEventListener("ended", function() {
        alert("Song is finished!");
        self.next();
    });

}

see the MDN for more info on the this keyword

【讨论】:

  • 谢谢,我没看过那个。我试过使用那里提到的选项,但似乎也不起作用。我将使用新信息编辑问题。
  • 我认为两者都是正确的,但无论如何,它也不起作用:S
  • 哦!它可以使用它!我只是尝试相同但使用 jQuery,即 var me = $(this);它没有用,但它适用于您的代码!非常感谢!
  • 好的,很酷..您需要在javascript中使用关键字this小心行事..查看this上的Mozilla文档:developer.mozilla.org/en/JavaScript/Reference/Operators/this
  • 感谢您的链接,将派上用场。顺便说一句,正如我之前提到的,当函数有名称时它会起作用,即我一直使用 `this.next = function next(){...}',所以这并不会真正影响结果。
猜你喜欢
  • 2023-03-12
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 2014-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多