我写了一个愚蠢的例子来看看两者中的哪一个,click
or the submit
事件,首先在 type 的输入上触发submit
.
但是,当我运行它时,没有任何内容写入控制台。
在调试器中单步执行代码会发现以下一系列情况。
它会触发click
事件处理程序首先将文本“click”写入控制台,但不久之后,该文本从控制台消失。
另外,submit
事件永远不会被触发。
我推断表单是在执行后提交的click
按钮的事件。我不明白的是为什么它没有进入我的submit
事件处理程序?
下面是相关代码,这里是完整的工作示例 https://github.com/Sathyaish/Practice/blob/master/JavaScript/Language/ClickOrSubmit.html。它只是一个简单的 HTML 文件,您可以下载并在您的计算机上试用。
(function() {
let btn = document.getElementById("btnSave");
btn.addEventListener("click", function(event) {
console.log("click");
}, false);
btn.addEventListener("submit", function(event) {
console.log("submit");
// event.preventDefault();
}, false);
console.log("All done now. Click da button, chum, click it I say!");
})();
div { margin: 20px; }
input[type="submit"] { width: 200px; height: 50px; }
<div>Look at the console and then click the button, chum!</div>
<div>
<form>
<input type="submit" id="btnSave" value="Save" width="200px" />
</form>
</div>
我不明白的是为什么它没有进入我的提交事件处理程序?
input
元素没有submit
事件。你需要挂钩submit
on the form
,不是input
.
btn.form.addEventListener("submit", function(event) {
// ^^^^^
console.log("submit");
event.preventDefault();
}, false);
(btn.form
可能有btn.closest("form")
如果你愿意的话btn.form
得到更广泛的支持并且(也)标准化 https://html.spec.whatwg.org/#dom-fae-form。或者,当然,使用getElementById
or querySelector
检索form
元素。)
实例:
(function() {
let btn = document.getElementById("btnSave");
btn.addEventListener("click", function(event) {
console.log("click");
}, false);
btn.form.addEventListener("submit", function(event) {
// ^^^^^
console.log("submit");
event.preventDefault();
}, false);
console.log("All done now. Click da button, chum, click it I say!");
})();
div {
margin: 20px;
}
input[type="submit"] {
width: 200px;
height: 50px;
}
<div>Look at the console and then click the button, chum!</div>
<div>
<form>
<input type="submit" id="btnSave" value="Save" width="200px" />
</form>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)