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 获得发生事件的控件,在事件响应函数调用的函数中不能使用
<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 是引发事件的对象,这个区别在事件冒泡中很明显 。