javascript 事件触发机制
直入正题:
<div id="box" class="blue">
box
<div id="child-box" class="blue">
child box
</div>
</div>
<button id="btn">触发事件</button>
<
script>
var evt = new Event('customEvent');
var eventBox = document.getElementById('box');
var eventChildBox = document.getElementById('child-box');
function customEventCallback(e) {
console.log('run ' + e.target.getAttribute('id'));
}
eventChildBox.addEventListener('customEvent', customEventCallback, false);
eventBox.addEventListener('customEvent', customEventCallback, false);
//测试代码
var btn = document.getElementById('btn');
btn.onclick = function(e) {
eventChildBox.dispatchEvent(evt);
};
为什么单击按钮只会触发一次,且输出是
run child-box
哪位大师能指点一下?
东風谷早苗
10 years, 3 months ago