javascript addEventListener onStateChange not working in IE

家住魔仙堡 提交于 2019-11-30 21:11:22
Raine

from testing in IE it looks like the reference you are using

ytswf = document.getElementById('ytplayer1');

is assigned before the actual swf object is loaded, so IE thinks you are referring to a simple div element

you need to run this code

function onYouTubePlayerReady(playerId) {
  ytswf = document.getElementById("ytplayer1");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

right after you call

swfobject.embedSWF("http://www.youtube.com/v/SPWU-EiulRY?
hl=en_US&hd=0&rel=0&fs=1&autoplay=1&enablejsapi=1&playerapiid=ytvideo1",
"popupVideoContainer1", "853", "505", "8", null, null, params, atts);

before you close out that $(function()

and place var ytswf; right after the <script> instead of further down

IE doesn't support addEventListener does it?? You need attachEvent right?

if (el.addEventListener){   
    el.addEventListener('click', modifyText, false);    
else if (el.attachEvent){   
    el.attachEvent('onclick', modifyText);   
}

New answer

The YouTube player object implements its own addEventListener method which is more like how AS3's syntax. As per the information listed here:

player.addEventListener(event:String, listener:String):Void

YouTube provides an example on the page I linked which I'll provide here:

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
   alert("Player's new state: " + newState);
}

YouTube also provides an example page that seems to prove out that their example code works in IE. I'll link that example page here.

Now, here's an attempt at re-writing the pertinent parts of your code to work as per the examples provided by Google/YouTube:

function onYouTubePlayerReady(playerId) {
  if(playerId && playerId == 'ytvideo1'){
    var ytplayer = document.getElementById('ytplayer1');
  } else if(playerId && playerId == 'ytvideo2'){
    var ytplayer = document.getElementById("ytplayer2");
  } else {
    return;
  }

  ytplayer.addEventListener('onStateChange', 'onytplayerStateChange');
}

So, it turns out that the mistake being made here arises from the confusion created by the use of the method name 'addEventListener'. In the W3C JavaScript implementation, the second parameter is a function while in the YouTube implementation, the second parameter is a string. Give this a shot =).

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