javascript 检查表单是否已经存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8178742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if form already exists
提问by Joe
Is there a better command than this to check if a form is exists and if so submit it? Right now I'm using:
有没有比这更好的命令来检查表单是否存在,如果存在则提交它?现在我正在使用:
if(document.forms[0])document.forms[0].submit()
Which works, however if form[0] does not exist it throws an exception. I'm trying to keep this dynamic in the sense I don't know what the form ID or name is.
哪个有效,但是如果 form[0] 不存在,它会引发异常。我试图保持这种动态,因为我不知道表单 ID 或名称是什么。
回答by Jonathan M
To avoid the exception you could do:
为避免异常,您可以执行以下操作:
if (typeof document.forms[0] !== 'undefined') document.forms[0].submit();
回答by RoccoC5
If your only requirement is to check whether a form exists, and if so, submit the first form, you can use:
如果您唯一的要求是检查表单是否存在,如果存在,提交第一个表单,您可以使用:
if (document.forms.length) document.forms[0].submit();
回答by Sarfraz
回答by Jason
can you add an id to the form? can you use jquery?
你能在表格中添加一个id吗?你会用jquery吗?
with id, no jquery
有 id,没有 jquery
var form = document.getElementById('my-form');
if (form != null) {
form.submit();
}
with id & jquery
带有 id 和 jquery
if ($("#my-form").length == 1) {
$("#my-form").submit();
}