不能直接将[audio] .play()作为jQuery回调 [英] Can't directly have [audio].play() as a jQuery callback

查看:155
本文介绍了不能直接将[audio] .play()作为jQuery回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

var music = $("audio")[0];
//doesn't work
$("#pbutton").click(music.play);
//works
$("#pbutton").click(function(){music.play()});

不起作用的行在Firefox中返回此错误:

The line that doesn't work returns this error in Firefox:

TypeError:在没有实现HTMLMediaElement接口的对象上调用'play'。

我在这里错过了什么吗?为什么这不起作用?

Am I missing something here? Why doesn't this work?

更新:我制作了一个小提琴为此。

Update: I made a fiddle for this.

推荐答案

这实际上非常简单。 我已更新您的小提琴以显示它。

That's actually pretty simple. I've updated your fiddle to show it.

var x = {
    play: function()
    { 
        console.log(this);
    }
};

$(document).ready(function()
{
    var music = document.getElementById("song");

    $("#play").click(function()
    {
        x.play();
    });

    $("#play").click(x.play);

    $("#pause").click(music.pause);
});

查看代码和开发人员控制台。在第一个单击处理程序中,您调用对象 x 的函数 play 。由于它是正常调用,函数中的 this x对象,这是正确的。

Look at the code and your developer console. In the first click handler you call the function play of the object x. Since it is "normal" invocation, the this in the function is the x object, which is correct.

作为您的第二个点击处理程序,您指向直接指向 x.play 功能。但是因为jQuery维护了你用作点击处理程序的函数的这个上下文,函数中的 this 现在是播放按钮。

As your second click handler you point directly to the x.play function. But because jQuery maintains the this-context of the function you use as click handler, the this in the function is now the play-button.

现在,如果播放功能中的某些内容使用了此变量,则会出现错误(因为在播放功能中,您认为是你的 x-object )。这就是为什么你经常需要围绕无参数函数包装匿名函数的原因 - 调用使其工作。

Now, if something in your play-function uses the this-variable, you get errors (because inside your play function you assume that this is your x-object). And that's the reason why you often have to wrap an anonymous function around a parameterless function-calls to make it work.

这篇关于不能直接将[audio] .play()作为jQuery回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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