gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:35:38 25 4
gpt4 key购买 nike

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

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

如果“ytplayer”的状态改变,foo 被执行!

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

是否可以在 foo() 函数中查询是什么触发了 foo() 函数?听起来很奇怪,很难解释。试想一下,我有多个 ytplayer,例如 ytplayer1、ytplayer2 等,并且每个视频在其状态发生变化后都会触发相同的 foo() 函数。

是否可以检索哪个 ytplayer 在 foo() 函数内触发了 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;
}

最佳答案

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

由于您似乎传递了一个已求值的字符串,因此您可能需要为每个字符串创建一个单独的函数:

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

关于事件触发的 Javascript 函数 - 获取目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5020070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com