事件触发Javascript函数 - 获取目标?

时间:2011-02-16 17:46:51

标签: javascript function events dom-events

我正在使用Youtube Javascript API,但它甚至可能不是与此API直接相关的问题。

ytplayer.addEventListener("onStateChange", "foo");

如果“ytplayer”的状态发生变化,foo就会被激活!

function foo() {
    //how to get "ytplayer" in here?
}

是否可以查询在foo()函数内部触发foo()函数的内容? 听起来很奇怪,很难解释。 想象一下,我有多个ytplayer,比如ytplayer1,ytplayer2等,一旦状态发生变化,每个视频都会触发相同的foo()函数。

是否有可能在foo()函数中检索哪个ytplayer触发了foo()函数? 对不起,我无法解释得更好! :)

编辑:

正好让你得到我正在做的事情!

/*Control Youtube videos with swfobject*/
function onYouTubePlayerReady() {
    var $ytid = '',
        ytid = '';
    $('object[id^="ytplayer_"]').each(function() {
        $ytid = $(this).attr('id');
        ytid = document.getElementById($ytid);
        ytid.addEventListener("onStateChange", "(function(status){foo(status,"+$ytid+");})");
        ytid.unMute(); 
        ytid.setVolume(100);
    });
};

function foo( status, player ) {
    console.log(status);
    console.log(player);
    //var pl = player;
}

2 个答案:

答案 0 :(得分:2)

似乎唯一可用的参数代表状态。

由于您似乎传递了一个被评估的String,您可能需要为每个创建一个单独的函数:

function foo( status, player ) {
    // do something with status and player
}

ytplayer1.addEventListener("onStateChange", "foo1");
function foo1( status ) {
    foo( status, ytplayer1 );
}

ytplayer2.addEventListener("onStateChange", "foo2");
function foo2( status ) {
    foo( status, ytplayer2 );
}

ytplayer3.addEventListener("onStateChange", "foo3");
function foo3( status ) {
    foo( status, ytplayer3 );
}

或者你可以尝试传递一个完整的匿名函数字符串:

function foo( status, player ) {
    // do something with status and player
}

ytplayer1.addEventListener("onStateChange", "(function(status){foo(status,ytplayer1);})");

ytplayer2.addEventListener("onStateChange", "(function(status){foo(status,ytplayer2);})");

ytplayer3.addEventListener("onStateChange", "(function(status){foo(status,ytplayer3);})");    

编辑: *在命名空间中创建唯一函数的一般示例。

    // gets called by the namespaced functions
function foo( status, player ) {
    // do something with status and player
}

  // create some namespace
window.myNamespace = {};

  // this gets called to create a new function in the namespace,
  //     and call addEventListener, which references the proper function
function funcFactory( player, i ) {

        // create a new function in myNamespace
    window.myNamespace[ "foo" + i ] = function( status ) {
        foo( status, player );
    };
        // Add event listener that calls that function
    player.addEventListener( "onStateChange", "window.myNamespace.foo" + i );
}

   // your loop
for( var i = 1; i < 10; i++ ) {
    var playa = someGeneratedPlayer();
    funcFactory( playa, i );
}

答案 1 :(得分:1)

应包含所需的对象。