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

来源:互联网 发布:java开源cms 编辑:程序博客网 时间:2024/06/06 02:43

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

验证:

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

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

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

    <input id="Button1" type="button" value="button1" onclick="alert(event.srcElement.value)" />    <input id="Button2" type="button" value="button2" onclick="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" onclick="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" onclick="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" onclick="btnclick1()" /></body></html>

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





原创粉丝点击