read table of contents
JavaScript traverses the source code of all controls from the form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>演示文档</title>
<style type="text/css">
/* input{background: green}
input[type=submit]{
background: orange
}*/
</style>
</head>
<body>
<form action="#" method="post" name="form01">
<p>昵称:<input type="text" name="username"></p>
<p>密码:<input type="password" name="password"></p>
<p><input type="submit" value="提交"></p>
</form>
<script type="text/javascript">
function getFele(){
var fele=form01.elements;
// alert(fele.length)
for(var i=0;i<fele.length;i++){
var e=fele[i];
if (e.type=='submit') {
e.style.background='orange'
}else if(e.type=='password'){
e.style.background='rgb(232, 240, 254)'
}else{
e.style.background='green'
}
}
}
getFele()
</script>
</body>
</html>
Source code analysis
1. Get all the elements in the form:
Pass formelement.elements
, where the form element is directly located through the name attribute.
var fele=form01.elements;
2. Loop traversal to get specific elements: through elements[i]
the form of
The first two steps can traverse all the controls of the form
var e=fele[i];
3. Determine whether the type of a control is a type: through element.type
if (e.type=='submit') {
}
JavaScript access form (four methods)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>演示文档</title>
<style type="text/css">
form{
width: 300px;
height: 150px;
background: green;
margin:25px;
}
</style>
</head>
<body>
<form action="" name="myform1">表单1</form>
<form action="" name="myform2">表单2</form>
<form action="" name="myform3">表单3</form>
<form action="" name="myform4">表单4</form>
<script type="text/javascript">
//访问表单的的方式1
document.getElementsByTagName('form')[0].style.background='red';
//访问表单的的方式2
// alert(document.forms.length)
document.forms[1].style.background='orange';
//访问表单的的方式3
document.forms['myform3'].style.background='blue';
//访问表单的的方式4
//不推荐使用,因为页面中表单较多的情况下容易出现相同name
myform4.style.background='pink'
</script>
</body>
</html>
Source code analysis
1. The way to access the form 1: the getElement method of document
document.getElementsByTagName('form')[0].style.background='red';
2. The way to access the form 2: the forms attribute of the document
// alert(document.forms.length)
document.forms[1].style.background='orange';
3. The way to access the form 3: The form attribute of document t and the name attribute of form are precisely positioned
document.forms['myform3'].style.background='blue';
4. Ways to access the form 4: precise positioning of the name attribute of the form
//不推荐使用,因为页面中表单较多的情况下容易出现相同 name
myform4.style.background='pink'