您的位置:首页 > Web前端 > JavaScript

Javascript中的事件冒泡

2009-02-18 14:21 288 查看
这是一个基础性的文章,使用Javascript观察DOM中的事件冒泡机制,并介绍如何阻止默认行为和如何组织事件冒泡的方法。

1. 第一个例子可以在Firefox下运行

<div id="container1" onclick="alert('click container1');">
<div id="container2" onclick="alert('click container2');">
<a href="http://www.google.com" target="_blank" onclick="fn1(event);">Google</a>
<a href="http://www.google.com" target="_blank" onclick="fn2(event);">Google</a>
<a href="http://www.google.com" target="_blank" onclick="fn3(event);">Google</a>
<a href="http://www.google.com" target="_blank" onclick="fn4(event);">Google</a>
</div>
</div>

function fn1(event) {
alert('click google');
}

function fn2(event) {
alert('click google');
event.preventDefault();
}

function fn3(event) {
alert('click google');
event.stopPropagation();
}

function fn4(event) {
alert('click google');
event.preventDefault();
event.stopPropagation();
}

点击第一个链接,alert_google -> alert_container2 -> alert_container1 -> open_google_page

点击第二个链接,alert_google -> alert_container2 -> alert_container1

点击第三个链接,alert_google -> open_google_page

点击第四个链接,alert_google

可以看到,事件冒泡是从最初引发事件的HTML节点开始,一步步向上引发父节点的相同事件。

在Firefox中,我们可以通过 preventDefault 函数阻止默认的行为(比如这个例子中,点击链接的默认行为是打开链接地址)

通过 stopPropagation 函数阻止事件冒泡。

相同的过程在IE下的实现有点不同,一是事件对象(event)在IE下是作为 window 对象的一个属性,

二是阻止事件的默认行为或阻止事件冒泡的做法也有所不同,请看:

2. 观察IE下的事件冒泡

<div id="container1_ie" onclick="alert('click container1');">
<div id="container2_ie" onclick="alert('click container2');">
<a href="http://www.google.com" target="_blank" onclick="fn1_ie();">Google</a> <a
href="http://www.google.com" target="_blank" onclick="fn2_ie();">Google</a>
<a href="http://www.google.com" target="_blank" onclick="fn3_ie();">Google</a> <a
href="http://www.google.com" target="_blank" onclick="fn4_ie();">Google</a>
</div>
</div>

function fn1_ie() {
alert('click google');
}

function fn2_ie() {
alert('click google');
event.returnValue = false;
}

function fn3_ie() {
alert('click google');
event.cancelBubble = true;
}

function fn4_ie() {
alert('click google');
event.returnValue = false;
event.cancelBubble = true;
}

同样:

点击第一个链接,alert_google -> alert_container2 -> alert_container1 -> open_google_page

点击第二个链接,alert_google -> alert_container2 -> alert_container1

点击第三个链接,alert_google -> open_google_page

点击第四个链接,alert_google

代码下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: