简体   繁体   English

运行for循环以在JavaScript中打印输入框的类型

[英]Running a for loop to print type of input boxes in JavaScript

I have this idea that I wanted to try out. 我有这个想法,我想尝试一下。 I have a form which has a certain number of input elements inside it. 我有一个表单,里面有一定数量的输入元素。 I want to run a function that will print out the type of the input elements using two for loops. 我想运行一个函数,它将使用两个for循环打印出输入元素的类型。 Here is the code that I tried out 这是我试过的代码

                  function check(){         
                     var i = document.forms.length;
                     var j = document.forms[i-1].elements.length;
                    //alert(i);
                   //  alert(j);
                    for (var k=0; k<=i;k++){
                    //alert(l);
                         for (var l=0;l<=j;l++){  
                          //alert(l);
                          alert(document.forms[k].elements[l].type);
                          }
                      }
                  }  

The code only prints out the type of the first element in the form. 代码只打印出表单中第一个元素的类型。 What am I doing wrong ? 我究竟做错了什么 ?

get all the forms in your page, loop thru each forms, inside first loop get the elements specific to the form which is currently being iterated, loop thru the elements and get the type, try doing: 获取页面中的所有表单,循环遍历每个表单,在第一个循环中获取特定于当前正在迭代的表单的元素,循环通过元素并获取类型,尝试执行:

var frms = document.forms;
for(var f = 0; f < frms.length; f++ ) {
    var elems = frms[f].elements;
    for(var e = 0; e < elems.length; e++ ) {
        console.log( elems[e].type );
    }
}

Demo:: jsFiddle 演示:: jsFiddle

Can you use querySelectorAll ? 你能使用querySelectorAll吗?

var elems = document.querySelectorAll("form input");
for(var i in elems) {
  console.log(elems[i].type);
}

If not, you need to count the elements for the form inside your first for loop: 如果没有,您需要在第一个for循环内计算表单的元素:

function check(){         
  var i = document.forms.length;       
  for (var k=0; k<i;k++){
    // Check the element length here
    var j = document.forms[k].elements.length;
    for (var l=0;l<j;l++){  
      alert(document.forms[k].elements[l].type);
    }
  }
 }  

I tried your script and works well with the following modifications: 我尝试了你的脚本,并在以下修改中运行良好:

First Loop for (var k=0; k<=i-1;k++) { 第一个循环for (var k=0; k<=i-1;k++) {

Second Loop for (var l=0;l<=j-1;l++){ 第二个循环for (var l=0;l<=j-1;l++){

Otherwise you have an error cause all loops are executed +1 times. 否则您会出错,导致所有循环执行+1次。

I wrote simple jsfiddle example - http://jsfiddle.net/REb64/ 我写了简单的jsfiddle示例 - http://jsfiddle.net/REb64/

      function check(){   
        for (var i=0; i < document.forms.length; i++){
          for (var j=0; j < document.forms[i].elements.length; j++){
            alert(document.forms[i].elements[j].type);
          }
        }
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM