随笔 - 173  文章 - 1  评论 - 26  阅读 - 43万

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 on   HorseShoe2016  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示