使用 element.addEventListener 的正确方法 [英] Correct way of using element.addEventListener

查看:112
本文介绍了使用 element.addEventListener 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 JavaScript 函数,它们充当触发自定义事件的 <object/> 对象的事件侦听器.有问题的对象是启用了 JavaScript API 的 YouTube 播放器.文档 提供了用于附加事件侦听器的示例代码:

I have a few JavaScript functions that behave as event listeners for an <object/> object which fires custom events. The object in question is the JavaScript API enabled YouTube player. The documentation provides this example code for attaching event listener:

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
  // note: quotes used ----------------------^---------------------^
  // note: callback function defined in an arbitrary location
}
function onytplayerStateChange(newState) {
   alert("Player's new state: " + newState);
}

但是,根据 addEventListener 示例我在别处看到不建议使用引号:

However, according to the addEventListener examples I've seen elsewhere do not suggest using quotes:

function onytplayerStateChange(newState) {
   alert("Player's new state: " + newState);
}
function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  // note: callback function defined EARLIER
  ytplayer.addEventListener("onStateChange", onytplayerStateChange);
}

那么哪种方法是正确的呢?第一个似乎适用于所有浏览器,但最近我注意到一些奇怪的问题,我想知道这些问题是否与调用 addEventListener 的方式有关.

So which method is right? The first one appeared to work in all browsers but recently I notice strange problems and I wonder if those problems are related with the way addEventListener is called.

推荐答案

由于 addEventListener 方法实际上是在 Flash Player 中公开的方法,而不是原生的 addEventListener,因此它实际上取决于 YTPlayer 内部 AS3 代码的实现.

Since the addEventListener method is actually a method exposed in the flash player and not the native addEventListener, it really depends on the implementation of the AS3 code inside the YTPlayer.

我会使用文档并使用引号

I would go with the documentations and use the quotes

这篇关于使用 element.addEventListener 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆