首页 > 解决方案 > 将自动参数传递给 javascript 函数的 HTML 功能的名称是什么?

问题描述

在此 HTML 中,对象event被传递给函数并在目标 javascript 函数中使用:

<!DOCTYPE html>
<html>

<body onclick="myFunction(event)">

  <p>Click on a paragraph. An alert box will alert the element that triggered the event.</p>
  <p><strong>Note:</strong> The target property returns the element that triggered the event, and not necessarily the eventlistener's element.
  </p>

  <script>
    function myFunction(event) {
      alert(event.target.nodeName);
    }
  </script>

</body>

</html>

资源

event现在,如果在 HTML 中更改传递参数的名称,例如更改为<body onclick="myFunction(e)">,脚本将不再工作,这证明 HTML 有一个默认对象列表,可以输入到 javascript 函数调用中。我们是否知道这些默认命名对象的列表以及它们在文档中是如何描述的?

标签: javascripthtml

解决方案


您可以使用eventthis。根据MDN

当事件处理程序被指定为 HTML 属性时,指定的代码将被包装到具有以下参数的函数中:

  • event— 对于除onerror.
  • event, source, lineno, colno, 和error用于onerror事件处理程序。请注意,事件参数实际上包含作为字符串的错误消息。

调用事件处理程序时,处理程序this内的关键字设置为注册处理程序的 DOM 元素。有关更多详细信息,请参阅this 关键字文档


推荐阅读