html 元素的 onEvent 与 addEventListener

对于 html 元素的 onEvent,我们想要给其添加 function handler() {},有时候会弄不清楚到底是添加

<div onEvent="handler">

还是添加

<div onEvent="handler()">

下面三个等价的 input 标签说明了正确的方法:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Event Listener</title>
  </head>
    <input type="file" id="myFile"  name="file1" />
    <input type="file" onchange="showFile(this)" name="file2" />
    <input type="file" onchange="handler(event)" name="file3" />

    <script>
      // 可以直接通过 id 字符串引用元素
      myFile.addEventListener('change', handler)

      function handler(event) {
        showFile(event.target) 
      }
      function showFile(input) {
        let file = input.files[0]
        let str =
          `input.name: ${input.name}\n` +
          `File name: ${file.name}\n` + // 例如 my.png
          `Last modified: ${file.lastModified}\n` // 例如 1552830408824
        alert(str)
      }
    </script>
  </body>
</html>

即我们应当添加

<div onEvent="handler(event)"> // 如果要接收事件,参数必须写成 event
posted @ 2024-04-09 14:39  HorseShoe2016  阅读(6)  评论(0编辑  收藏  举报