Javascript中的事件冒泡
這是一個基礎性的文章,使用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
?
代碼下載
轉載于:https://www.cnblogs.com/sanshi/archive/2009/02/18/1393165.html
總結
以上是生活随笔為你收集整理的Javascript中的事件冒泡的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET 指南:捕获并且抛出标准的异常类
- 下一篇: 利用XMLSerializer将对象串行