element.addEventListener 的正确使用方法
我有一些 JavaScript 函数,它们充当触发自定义事件的
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于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