Dom笔记7:事件冒泡以及事件中的this

1:事件冒泡:如果元素 A 嵌套在元素 B 中,那么 A 被点击不仅 A 的onclick 事件会被触发, B 的 onclick 也会被触发。触发的顺序是 “ 由内而外 ”   。

验证:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>无标题页</title>
</head>
<body  οnclick="alert('body被触发')">
<table><tr  οnclick="alert('tr被触发')"><td  οnclick="alert('td被触发')">
    <input id="Button1" type="button" value="button" οnclick="alert('按钮被触发')"/>
    </td></tr></table>
</body>
</html>
运行可以知道,一旦点击按钮,则不仅按钮的onclick事件被触发,一级一级,由内而外,都会被自动触发。

由此,可以明白,要想监听某一个事件,不一定要监听到具体事件,监听他的上一级事件也可以。

2: 事件中的 this 。
两种获取当期发生事件的控件:event.srcElement和this

    <input id="Button1" type="button" value="button1" οnclick="alert(event.srcElement.value)" />
    <input id="Button2" type="button" value="button2" οnclick="alert(this.value)" />


注意: this 表示发生事件的控件 ,只有在事件响应函数才能使用 this 获得发生事件的控件,在事件响应函数调用的函数中不能使用

如果我们这样使用this,是错误的:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>无标题页</title>
    <script type="text/javascript"">
    function btnclick1()
    {
       alert(this.value);//注意,this在事件响应函数调用的函数中不能获得事件对象
    }
    
    </script>
</head>
<body>
    
    <input id="Button1" type="button" value="button1" οnclick="btnclick1()" />
</body>
</html>

如果要使用则要将 this 传递给函数或者使用event.srcElement 。

传递this参数:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>无标题页</title>
    <script type="text/javascript"">
    function btnclick1(btn)
    {
       alert(btn.value);
    }
    
    </script>
</head>
<body>
    
    <input id="Button1" type="button" value="button1" οnclick="btnclick1(this)" />
</body>
</html>

或者使用event.srcElement:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>无标题页</title>
    <script type="text/javascript"">
    function btnclick1()
    {
       alert(event.srcElement.value);
    }
    
    </script>
</head>
<body>
    
    <input id="Button1" type="button" value="button1" οnclick="btnclick1()" />
</body>
</html>

一定要注意:this 和 event.srcElement 的语义是不一样的, this 就是表示当前监听事件的这个对象, event.srcElement 是引发事件的对象,这个区别在事件冒泡中很明显 。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值