以前一直不在意這個事件冒泡,只是有時候會用到stopPropagation()
去阻止事件冒泡,最近發現,利用好了事件冒泡這一特性,有些地方會非常方便。
拿個最直觀的例子來舉例 ToolBar
界面
HTML
<div id="toolbar" class="btn-toolbar" role="toolbar" aria-label="...">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default">Left</button>
<button type="button" class="btn btn-default">Middle</button>
<button type="button" class="btn btn-default">Right</button>
</div>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default">Close</button>
</div>
</div>
以前我是給每一個按鈕綁定一個事件,這裏不做例子了,直接寫如何利用事件冒泡這一特性進行綁定。
var toolbar = {
Left: function () {
alert('Left');
},
Middle: function () {
alert('Middle');
},
Right: function () {
alert('Right');
},
Close: function () {
alert('Close');
}
}
document.getElementById('toolbar').onclick = function (e) {
var fun = toolbar[e.target.textContent];
if (fun) { fun(); }
};
直接給這些按鈕所在的 #toolbar
綁定click事件,然後通過 e.target
可以得到對按鈕的引用,最後再根據textContent對按鈕文本進行判斷即可。