代码
html
<form id="myFrm" name="myFrm" action="/myApp/ProcessFrm" method="post">
<input autofocus="autofocus" type="text" id="Location" name="Location" onkeydown="changetotab()" style="width: 4em" tabindex="1" />
<input type="Submit" value="Submit" id="submit" /> <br />
</form>
js
function changetotab() {
var charCode = (window.event.which) ? window.event.which : window.event.keyCode;
if (charCode == 13 || charCode == 9) {
if (document.myFrm.submit == undefined) {
alert("form submit can't be found")
} else {
alert("form can be submitted");
document.myFrm.submit();
}
}
}
发生的事情是,当用户按下 TAB 或 ENTER 时,document.myFrm.submit == undefined 出现 false(到目前为止一切正常);然后发生了一些奇怪的事情 - 当我到达 document.myFrm.submit(); JS提示找不到这个方法。
0x80020003 - JavaScript runtime error: Member not found.
这里发生了什么?
注意:我不能使用 Jquery,以防万一你想知道我为什么使用旧式 JS。这将在不支持 Jquery 的旧设备上运行。
最佳答案
参见 this JSfiddle .这里发生了什么?好吧,在出现 DOM 时代之前,JavaScript 为每个 input
创建了一个属性 foo
,在 input
上命名为 foo
> 的父 form
:
form.foo.toString() === "HTMLInputElement";
然而,这意味着,如果您有一个名称为 submit
的输入元素,表单自己的 submit
方法将被覆盖。这种行为一直延续到今天。
现在,您的输入没有 name
属性。在这种情况下,行为是从 input
的 ID 中推断出一个,如果一个被设置的话。所以基本上,更改 input
的 ID,这是处理它的最直接的方法:
<input type="Submit" value="Submit" id="submit_" />
不幸的是,有很多这样的微妙之处。参见 DOMLint以获得良好的概述。
编辑:如果您最终遇到了损坏的 submit
方法并且无法更改 HTML,该怎么办?然后从表单的原型(prototype)中获取提交方法并使用它:
// form.submit() doesn't work, but this will:
HTMLFormElement.prototype.submit.call(form);
关于javascript - 在 Javascript 中找不到 Form.submit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22868547/