为什么其中一个侦听器适用于媒体 API 事件,而另一个则不适用于媒体 API 事件

Why does one of these listeners work for a Media API event but not the other?

本文关键字:适用于 事件 API 媒体 不适用 另一个 侦听器 一个 为什么      更新时间:2023-09-26

我正在为媒体 API 事件添加侦听器,如下所示:

function addPlayListener() {
    var video = document.getElementById("theVideo");
    video.addEventListener('play',  function() {alert('play');}, false); // method a
video.addEventListener('play',  alert('play'), false); // method b
}
window.addEventListener('load', addPlayListener, false);

<video id="theVideo" controls width="180" height="160" src="sample_mpeg4.mp4"> </video> 

使用方法 a 一切都按预期工作,但是使用方法 b,页面加载后立即显示警报(并且在事件触发时不显示)。

为什么会这样,方法 b 的语法有问题吗?

根据 addEvenListener 文档:

 target.addEventListener(type, listener[, useCapture]);

listener必须是:

  • 对象, 实现EventListener接口,
  • JavaScript 函数

alert()函数不返回任何实现EventListener接口的对象,也不返回Javascript function。简单地说,alert不返回任何内容。所以,你得到的是:

  video.addEventListener('play',  undefined , false);   //method b

addEventListener 的第二个参数必须是"在发生指定类型的事件时接收通知的对象。这必须是实现 EventListener 接口的对象,或者只是一个 JavaScript 函数。在您的"方法 b"中,警报会立即触发,因为它不在函数内,也不是实现 EventListener 接口的对象。方法 A 是普遍接受的语法。

method b 中,对话框会立即显示,因为您首先调用它 - alert('play')addEventListener不能延迟其参数的执行,而是传递alertreturn值 - 它不能做太多事情:

// what's being passed after `alert('play')` is called
video.addEventListener('play', true, false);

method a 中的function () { ... }正是延迟alert('play')调用直到触发事件所需的。a函数本身被传递给addEventListener,并且可以在以后调用任意次数(即事件的每个触发器)。并且,每次调用时,它都会依次执行其内容。