我有一个系统,其中主要内容通过 ajax 加载,位于主“框架”的 div 内。
在某些页面中,我需要跟踪用户何时完成播放视频。我正在尝试使用 youtube iframe api。它工作正常,但我正在处理一些奇怪的事情。
主要问题:当用户观看完视频时,每个页面上发生的动作是不同的,不知何故,API 正在堆叠所有功能并一次运行。
例如,我有第一页,它是通过 ajax 加载的,并且有这个片段来加载 youtube 视频:
<script>
// 2. This code loads the IFrame Player API code asynchronously.
if (window.YT)
{
window.YT = undefined;
}
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player = undefined;
function onYouTubeIframeAPIReady() {
player = new YT.Player('divVideo', {
playerapiid: 'somecode',
height: '309',
width: '439',
videoId: 'somecode',
events: {
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED ) {
actionToScreen1()
}
}
</script>
它工作正常。但是,我为我的第二页加载了内容,现在问题开始了:
<script>
// 2. This code loads the IFrame Player API code asynchronously.
if (window.YT)
{
window.YT = undefined;
}
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player = undefined;
function onYouTubeIframeAPIReady() {
player = new YT.Player('divVideo', {
playerapiid: 'anothercode',
height: '309',
width: '439',
videoId: 'anothercode',
events: {
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED ) {
actionToScreen2()
}
}
</script>
当我的 screen2 上的视频播放完毕后,onPlayerStateChange 会被调用两次,一次调用 actionToScreen1,另一次调用 actionToScreen2。看起来我只是通过 ajax 加载容器,该函数在某种程度上存储在全局范围内,但我找不到位置,也找不到区分调用哪个函数的方法。我怎样才能解决这个问题?