您现在的位置:首页 >> 前端 >> 内容

target事件属性、currentTarget事件属性、this代码实例介绍

时间:2017/10/28 11:40:21 点击:

  核心提示:target 事件属性可返回事件的目标节点(触发该事件的节点),如生成事件的元素、文档或窗口。currentTarget 事件属性返回其监听器触发事件的节点,即当前处理该事件的元素、文档或窗口一般来说...

target 事件属性可返回事件的目标节点(触发该事件的节点),如生成事件的元素、文档或窗口。

currentTarget 事件属性返回其监听器触发事件的节点,即当前处理该事件的元素、文档或窗口

一般来说,this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象 (实际上es6的箭头函数是在函数定义的时候就确定了this的指向)

    var name ='windows'
    var o ={
        name: 'o',
        f: function(){
            console.log(this.name)
        }
    }
    o.f()  //输出结果为'o'
    var name ='windows'
    var o ={
        name: 'o',
        f: ()=>{
            console.log(this.name)
        }
    }
    o.f()输入结果为'windows'
    var变量实际就是绑定到了window对象上

一般来说,this和event.currentTarget是一致的,但是this的作用域容易受到改变,event.currentTarget则保持不变,指向事件绑定的节点

event.target则指向触发该事件的节点

测试代码如下

    <p id='p'>
        <p><span>2</span></p>
    </p>
    <script type="text/javascript">
        document.querySelector('#p').onclick=function(){
            console.log(event.target)
            console.log(event.currentTarget)
            console.log(this)
        }
    </script>
<script type="text/javascript"> document.querySelector('#p').onclick=function(){ console.log(event.target) console.log(event.currentTarget) console.log(this) } </script>

点击p元素

target事件属性、currentTarget事件属性、this代码实例介绍

点击span元素

target事件属性、currentTarget事件属性、this代码实例介绍

修改代码如下

    <p id='p'>
        <p><span>2</span></p>
    </p>
    <script type="text/javascript">
        document.querySelector('#p').onclick=function(){
            (function(){
                console.log(event.target)
                console.log(event.currentTarget)
                console.log(this)
            })()
        }
    </script>
<script type="text/javascript"> document.querySelector('#p').onclick=function(){ (function(){ console.log(event.target) console.log(event.currentTarget) console.log(this) })() } </script>

点击p元素

target事件属性、currentTarget事件属性、this代码实例介绍

点击span元素

target事件属性、currentTarget事件属性、this代码实例介绍

Tags:TA AR RG GE 
作者:网络 来源:小前端