leer tabla de contenido
JavaScript atraviesa el código fuente de todos los controles del formulario
<!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>
Análisis de código fuente
1. Obtenga todos los elementos del formulario form:
Pass formelement.elements
, donde el elemento del formulario se ubica directamente a través del atributo name.
var fele=form01.elements;
2. Recorrido de bucles para obtener elementos específicos: a través de elements[i]
la forma de
Los dos primeros pasos pueden atravesar todos los controles del formulario.
var e=fele[i];
3. Determinar si el tipo de un control es un tipo: mediante elemento.tipo
if (e.type=='submit') {
}
Formulario de acceso JavaScript (cuatro métodos)
<!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>
Análisis de código fuente
1. La forma de acceder al formulario 1: el método getElement del documento
document.getElementsByTagName('form')[0].style.background='red';
2. La forma de acceder al formulario 2: el atributo formularios del documento
// alert(document.forms.length)
document.forms[1].style.background='orange';
3. La forma de acceder al formulario 3: El atributo de formulario del documento t y el atributo de nombre del formulario están posicionados con precisión
document.forms['myform3'].style.background='blue';
4. Formas de acceder al formulario 4: posicionamiento preciso del atributo nombre del formulario
//不推荐使用,因为页面中表单较多的情况下容易出现相同 name
myform4.style.background='pink'