練習
Bubble and Capture
<div>
<div id="parent">
我是父
<div id="child">我是子</div>
</div>
</div>
var parent = document.getElementById('parent');
var child = document.getElementById('child');
//執行內容要用function包起來, 不能直接alert, 不然documentload完就執行
parent.addEventListener(
'click',
function () {alert('from parent');},
false
);
child.addEventListener(
'click',
function () {alert('from child');},
false
);
//true(捕獲):從外往內執行 parent->child
//false(冒泡):從內往外執行 child->parent
parent.addEventListener('click',
function () {alert('parent bubble');},false
);
parent.addEventListener('click',
function () {alert('parent capture');},true
);
child.addEventListener('click',
function () {alert('child bubble');},false
);
child.addEventListener('click',
function () {alert('child capture');},true
);
//結果: parent capture->child capture->child bubble->parent bubble
<label class="label">
Label <input type="checkbox" id="check">
</label>
var label = document.querySelector('.label');
var check = document.querySelector('#check');
label.addEventListener('click',
function (e) {console.log('label');},false
);
//點擊Lable結果:
/*
"label"
"label"
*/
//新增event, 阻止傳遞(冒泡或補獲)
check.addEventListener('click',
function (e) {e.stopPropagation();},false
);
//點擊Lable結果:
/*
"label"
*/
用觸發事件的來源, 判斷是否阻止傳遞(冒泡或補獲)
var label = document.querySelector('.label');
var check = document.querySelector('#check');
label.addEventListener('click',
function (e) {
console.log(e.target.tagName, 'the label');
console.log(this.tagName, 'the label');
},
false
);
//結果:
/*
"LABEL", "the label"
"LABEL", "the label"
"INPUT", "the label"
"LABEL", "the label"
*/
//若要第三行"INPUT", "the label"結果不出現
label.addEventListener('click',
function (e) {
if (e.target.tagName!="INPUT"){
console.log(e.target.tagName, 'the label');
}
console.log(this.tagName, 'the label');
},
false
);
//結果:
/*
"LABEL", "the label"
"LABEL", "the label"
"LABEL", "the label"
*/