Javascript中的事件冒泡
這是一個(gè)基礎(chǔ)性的文章,使用Javascript觀察DOM中的事件冒泡機(jī)制,并介紹如何阻止默認(rèn)行為和如何組織事件冒泡的方法。
1. 第一個(gè)例子可以在Firefox下運(yùn)行
<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();
}
?
點(diǎn)擊第一個(gè)鏈接,alert_google -> alert_container2 -> alert_container1 -> open_google_page
點(diǎn)擊第二個(gè)鏈接,alert_google -> alert_container2 -> alert_container1
點(diǎn)擊第三個(gè)鏈接,alert_google -> open_google_page
點(diǎn)擊第四個(gè)鏈接,alert_google
?
可以看到,事件冒泡是從最初引發(fā)事件的HTML節(jié)點(diǎn)開始,一步步向上引發(fā)父節(jié)點(diǎn)的相同事件。
在Firefox中,我們可以通過?preventDefault 函數(shù)阻止默認(rèn)的行為(比如這個(gè)例子中,點(diǎn)擊鏈接的默認(rèn)行為是打開鏈接地址)
通過?stopPropagation 函數(shù)阻止事件冒泡。
?
相同的過程在IE下的實(shí)現(xiàn)有點(diǎn)不同,一是事件對(duì)象(event)在IE下是作為 window 對(duì)象的一個(gè)屬性,
二是阻止事件的默認(rèn)行為或阻止事件冒泡的做法也有所不同,請(qǐng)看:
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;
}
?
同樣:點(diǎn)擊第一個(gè)鏈接,alert_google -> alert_container2 -> alert_container1 -> open_google_page
點(diǎn)擊第二個(gè)鏈接,alert_google -> alert_container2 -> alert_container1
點(diǎn)擊第三個(gè)鏈接,alert_google -> open_google_page
點(diǎn)擊第四個(gè)鏈接,alert_google
?
代碼下載
轉(zhuǎn)載于:https://www.cnblogs.com/sanshi/archive/2009/02/18/1393165.html
總結(jié)
以上是生活随笔為你收集整理的Javascript中的事件冒泡的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET 指南:捕获并且抛出标准的异常类
- 下一篇: 第六届省赛(软件类)真题----Java