zoukankan      html  css  js  c++  java
  • JavaScript三种绑定事件的方式

    JavaScript三种绑定事件的方式:

      1. <div id="btn" onclick="clickone()"></div> //直接在DOM里绑定事件

        <script>

         function clickone(){ alert("hello"); }

        </script>

      2. <div id="btn"></div>

        <script>

         document.getElementById("btn").onclick = function(){ alert("hello"); } //脚本里面绑定

        </script>

      3. <div id="btn"></div>

        <script>

         document.getElementById("btn").addeventlistener("click",clickone,false); //通过侦听事件处理相应的函数

         function clickone(){ alert("hello"); }

        </script>

    那么问题来了,1 和 2 的方式是我们经常用到的,那么既然已经有两种绑定事件的方法为什么还要有第三种呢?答案是这样的:

    用 "addeventlistener" 可以绑定多次同一个事件,且都会执行,而在DOM结构如果绑定两个 "onclick" 事件,只会执行第一个;在脚本通过匿名函数的方式绑定的只会执行最后一个事件。

      1. <div id="btn" onclick="clickone()" onclick="clicktwo()"></div> 

        <script>

         function clickone(){ alert("hello"); } //执行这个

         function clicktwo(){ alert("world!"); }

        </script>

      2. <div id="btn"></div>

        <script>

         document.getElementById("btn").onclick = function(){ alert("hello"); }

         document.getElementById("btn").onclick = function(){ alert("world"); } //执行这个

        </script>

      3. <div id="btn"></div>

        <script>

         document.getElementById("btn").addeventlistener("click",clickone,false);

         function clickone(){ alert("hello"); } //先执行

         document.getElementById("btn").addeventlistener("click",clicktwo,false);

         function clicktwo(){ alert("world"); } //后执行

        </script>

  • 相关阅读:
    MTK 定时器 休眠时的动作
    Troubleshooting MySQL Memory Usage
    disruptor
    Google Protocol Buffer 的使用和原理
    百度贴吧10亿量级LAMP架构分享
    nginx 不带www到www域名的重定向
    配置电信网通双线双IP的解决办法
    Create a W3C validated anchor link with target=“_blank”
    Could not update ICEauthority file /home/username/.ICEauthority
    Can't load IA 32bit .dll on a AMD 64bit platform
  • 原文地址:https://www.cnblogs.com/thinkingthigh/p/9775966.html
Copyright © 2011-2022 走看看