element.addEventListener 的正确使用方法

发布于 2024-12-27 05:16:54 字数 1204 浏览 2 评论 0原文

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

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

但是,根据 < a href="https://developer.mozilla.org/en/DOM/element.addEventListener" rel="nofollow">addEventListener 我在其他地方看到的示例不建议使用引用:

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 的方式有关。

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷弦 2025-01-03 05:16:54

由于addEventListener方法实际上是flash播放器中公开的方法,而不是本机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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文