Blogger Information
Blog 47
fans 0
comment 3
visits 45065
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
事件的添加方式
江流
Original
1477 people have browsed it

事件的添加方式有四种:事件属性、元素对象、事件监听器、事件派发

  1. 事件属性
    以属性的方式,直接添加事件给html对象
    <button onclick="alert('hello')">事件属性</button>
    上面代码中的onclick就是事件属性
  2. 元素对象
  1. <button class="btn">元素对象</button>
  2. <script>
  3. const btn2 = document.querySelector(".btn");
  4. btn2.onclick = () => console.log(111);
  5. btn2.onclick = (_) => console.log(222);
  6. btn2.onclick = ($) => console.log(333);
  7. </script>

以此种方式添加的事件,后面的会覆盖前面的,只会输出“333”。如果要删除事件,可以在javascript中添加代码:
btn2.onclick = null;

3.事件监听器
使用addEventListener()方法事件监听器,给元素添加事件。格式如下:
addEventListener(事件类型, 事件回调,默认冒泡false/true捕获)

  1. <button class="btn-listener">事件监听器</button>
  2. <script>
  3. const btn3 = document.querySelector(".btn-listener");
  4. btn3.addEventListener("click", () => console.log(111));
  5. btn3.addEventListener("click", () => console.log(222));
  6. btn3.addEventListener("click", () => console.log(333));
  7. </script>

代码中的3行输出都能执行。此种方式不能删除事件。如果以此种方式添加并能够删除事件,必须将事件回调定义成函数。

  1. let show = () => console.log(444);
  2. btn3.addEventListener("click", show);
  3. // 删除
  4. btn3.removeEventListener("click", show);
  1. 事件派发
    通过dispatchEvent(),通过一个对象,将事件排发个预算对象。

    1. <button class="btn-dispatch">事件派发</button>
    2. <script>
    3. // 事件派发
    4. let i = 0;
    5. const btn4 = document.querySelector(".btn-dispath");
    6. btn4.addEventListener("click", () => {
    7. console.log("i=" + i);
    8. i += 0.5;
    9. });
    10. const myclick = new Event("click");
    11. btn4.dispatchEvent(myclick);
    12. btn4.dispatchEvent(myclick);
    13. setInterval(() => btn4.dispatchEvent(myclick), 2000);
    14. </script>
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post