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 获得发生事件的控件,在事件响应函数调用的函数中不能使用
<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 是引发事件的对象,这个区别在事件冒泡中很明显 。
- Dom笔记7:事件冒泡以及事件中的this
- JQuery DOM 事件冒泡
- JQuery DOM 事件冒泡
- Doc10(this,事件冒泡)
- 事件流(事件冒泡、事件捕获以及DOM事件流)
- js中的冒泡,捕获以及事件委托
- DOM事件阶段以及事件捕获与事件冒泡先后执行顺序(图文详解)
- DOM事件阶段以及事件捕获与事件冒泡先后执行顺序
- JS阻止DOM事件冒泡
- dom事件冒泡和捕获
- JS中的事件绑定,事件捕获,事件冒泡以及事件委托,兼容IE
- JS中的事件绑定,事件捕获,事件冒泡以及事件委托,兼容IE
- JS中的事件绑定,事件捕获,事件冒泡以及事件委托,兼容IE
- 事件流中的事件冒泡
- JS中的事件冒泡
- jquery中的事件冒泡
- Javascript中的冒泡事件
- Javascript中的事件冒泡
- 开博啦
- android 用gpio作为pwm输出控制led背光
- fzu 1719 Spy Network(强连通分量)
- php中iconv函数使用方法,URL传中文乱码问题,html页面跳转问题
- iphone和Objective-C笔试题
- Dom笔记7:事件冒泡以及事件中的this
- 为图片添加锚点
- ASP.NET读取Excel文件的三大方法浅析
- winform直方图饼图、直方图、曲线图
- 3D 地图编辑器
- PHP Warning: strtotime(): It is not safe to rely on the system's timezone settings
- 优先使用组合对象,而不是继承"的理解
- U盘使用心得
- ASP.NET+Ext js4.0----Viewport面板南北布局