要添加一个完全普通的JavaScript的解决方案,解决@ icedwater的问题表单提交,这里是一个完整的解决方案用form
。
注意:这适用于“现代浏览器”,包括IE9 +。IE8版本并不复杂,可以在此处学习。
小提琴:https : //jsfiddle.net/rufwork/gm6h25th/1/
的HTML
<body>
<form>
<input type="text" id="txt" />
<input type="button" id="go" value="Click Me!" />
<div id="outige"></div>
</form>
</body>
的JavaScript
// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://stackoverflow.com/a/21814964/1028230
document.addEventListener("DOMContentLoaded", function() {
var go = document.getElementById("go"),
txt = document.getElementById("txt"),
outige = document.getElementById("outige");
// Note that jQuery handles "empty" selections "for free".
// Since we're plain JavaScripting it, we need to make sure this DOM exists first.
if (txt && go) {
txt.addEventListener("keypress", function (e) {
if (event.keyCode === 13) {
go.click();
e.preventDefault(); // <<< Most important missing piece from icedwater
}
});
go.addEventListener("click", function () {
if (outige) {
outige.innerHTML += "Clicked!<br />";
}
});
}
});