您没有显示注册事件侦听器的实际代码。
让这个小提琴与 preventDefault 和 stopPropagation 一起玩。
我希望它是不言自明的。如果你愿意,可以叉小提琴。
请注意 form2.input 如何没有事件侦听器并且事件如何冒泡到 outerDiv。
form1 是根据相关的用户控件进行停止和阻止的那个。
输出区域应该澄清发生了什么。
HTML
<div id="outerDiv">
<div>
<input id="pd" value="1" type="checkbox">Prevent Default in form1 keydown</input>
</div>
<div>
<input id="sp" value="1" type="checkbox">Stop Propagation in form1 keydown</input>
</div>
<div>
<button id="clear">Clear Output</button>
</div>
<form id="form1" action="">
<div>
<label>input of form1
<input type="text" />
</label>
</div>
</form>
<form id="form2" action="">
<div>
<label>input of form2
<input type="text" />
</label>
</div>
</form> <pre id="output">
watch this spot
</pre>
</div>
JS
window.addEventListener('DOMContentLoaded', function (event) {
// console.log("DOMContentLoaded event handler ...");
var form1 = document.getElementById('form1');
var form2 = document.getElementById('form2');
var output = document.getElementById('output');
var div = document.getElementById('outerDiv');
var clear = document.getElementById('clear');
clear.addEventListener('click', function (event) {
output.textContent = ('\n' + clear.id + '\'s ' + event.type + ' event handler for ' + event.srcElement.localName + ' clears output');
}, false);
console.dir(output);
div.addEventListener('keydown', function (event) {
output.textContent += ('\n' + div.id + '\'s ' + event.type + ' event handler for ' + event.srcElement.localName + ' notices \'' + event.srcElement.value + '\'');
}, false);
form1.addEventListener('keydown', function (event) {
output.textContent += ('\n' + form1.id + '\'s ' + event.type + ' event handler for ' + event.srcElement.localName + ' notices \'' + event.srcElement.value + '\'');
// prevents default of generating an input event
if (document.getElementById('pd').checked) {
event.preventDefault();
output.textContent += ('\n\t' + form1.localName + '\'s ' + event.type + ' event handler does preventDefault');
}
// stops propagation up to div
if (document.getElementById('sp').checked) {
event.stopPropagation();
output.textContent += ('\n\t\t' + form1.localName + '\'s ' + event.type + ' event handler does stopPropagation');
}
}, false);
form1.addEventListener('input', function (event) {
output.textContent += ('\n' + form1.id + '\'s ' + event.type + ' event handler for ' + event.srcElement.localName + ' notices \'' + event.srcElement.value + '\'');
}, false);
}, false);