zoukankan      html  css  js  c++  java
  • 探究绑定事件的this指向以及event传参的小问题

    this指向


    直接上代码,凑合着看

    <input type="button" onclick="page()" value="点我"></input>
    <input type="button" value="点我2号" id="btn"/>
    <input type="button" value="点我3号" id="btn2"/>
    <input type="button" value="点我测试addEventListener传参" id="btn-parem"/>
    <input type="button" value="我是ie终结者,赶紧点我" id="ie-end">
    
    <script>
        //该函数用于测试页面上的this对象
        function page(){
            console.log(this==window)
    //        true 说明页面上绑定的事件的作用域都是window,这样很不好,因为有时候我们是希望我们的this值就是当前的对象而不是window
        }
    
        var btn=document.getElementById("btn");
        btn.onclick=function(){
            console.log(this);
    //        这个时候就正常了,输出的this指向的是当前的input对象
        };
    
        var btn2=document.getElementById("btn2");
        function btnClick(){
            console.log(this)
    //        很明显这也是正常的
        }
        btn2.addEventListener("click",btnClick,false);
    
    //    关于addEventListener我们再扯一个,怎么往addEventListener里面的函数传参
        var btnParem=document.getElementById("btn-parem")
        function pare(a,b){
            console.log(a+b)
        }
    //    btnParem.addEventListener("click",pare(1,2),false)
    //    亲,很明显这种写法是不行的,因为我还没点击事件就已经自动执行了
    
        btnParem.addEventListener("click",function(){pare(1,9)},false)
    
    //    注意,关于attachEvent该事件是ie特有的绑定事件方式,同时该事件以及渐渐的被抛弃,在最新的ie edge中已经没有了该事件转而支持addEventListener
    //    同时,在ie 9 10中也已经支持addEventListener事件
        var ieEnd=document.getElementById("ie-end")
        function ending(){
            console.log(this)
    //        在支持该事件的浏览器下输出window
        }
        ieEnd.attachEvent("onclick",ending)
    </script>
    

    怎么向addEventListener中传入event对象


    <input type="button" id="btn" value="测试"/>
    

    var btn=$("#btn");
    btn.onclick=function(e){
        console.log(e);
    }
    

    这样的写法是正常的,可以正确的传入e,换成addEventListener的情况就是这样写

    function func(e){
        console.log(e);
    }
    btn.addEventListener("click",func,false)
    

    此时可以看到,我们并没有显式的向func中传入参数e。那么当我们想传参的时候应该怎么写呢

    function func(e,a,b){
        console.log(e);
        console.log(a+b);
    }
    btn.addEventListener("click",function(e){
        func(e,1,2);
    },false);
    

    这就是正确的写法,使用一个匿名函数包住我们的func,同时在匿名函数中传入参数e

  • 相关阅读:
    vue使用elementui合并table
    使用layui框架导出table表为excel
    vue使用elementui框架,导出table表格为excel格式
    前台传数据给后台的几种方式
    uni.app图片同比例缩放
    我的博客
    【C语言】取16进制的每一位
    SharePoint Solution 是如何部署的呢 ???
    无效的数据被用来用作更新列表项 Invalid data has been used to update the list item. The field you are trying to update may be read only.
    SharePoint 判断用户在文件夹上是否有权限的方法
  • 原文地址:https://www.cnblogs.com/jelly7723/p/5658071.html
Copyright © 2011-2022 走看看