Can't directly have [audio].play() as a jQuery callback

对着背影说爱祢 提交于 2019-12-10 15:15:56

问题


Consider this code:

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

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

TypeError: 'play' called on an object that does not implement interface HTMLMediaElement.

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

Update: I made a fiddle for this.


回答1:


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

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.

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.

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.



来源:https://stackoverflow.com/questions/27476999/cant-directly-have-audio-play-as-a-jquery-callback

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