HTML中的表单:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" name="hello" id="login"> <input type="text" placeholder="demo@email.com" <button>提交</button> </form> </body> </html>
利用document.forms
获取当前页面的所有表单
document.forms[0]
获取当前页面的第一个表单
document.forms['hello']
通过表单的name属性获取表单
document.forms['login']
通过表单的id属性获取表单
<script> //form console.log(document.forms); // <form action="" name="hello" id="login"> console.log(document.forms[0]); console.log(document.forms['hello']); console.log(document.forms['login']); console.log(document.forms.item(0)); console.log(document.forms.item("hello")); console.log(document.forms.item("login")); //推荐 id console.log(document.forms.namedItem("login")); console.log(document.forms.hello); console.log(document.forms.login); </script>
推荐:《2021年js面试题及答案(大汇总)》
Atas ialah kandungan terperinci 如何在JavaScript中获取表单元素. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!