当我尝试计算密码字段时,下面的代码有什么问题

What is wrong with the below code when I am trying to count the password fields?

本文关键字:代码 问题 什么 计算 字段 密码      更新时间:2023-09-26

下面的代码有什么问题?根据琳达的说法,getElementsByTagName应该返回一个array,所以基本上它应该工作得很好。请帮忙向我解释出了什么问题?

var outputs= 0;
function countPasswds(){
    var v= document;
    d=v.getElementsByTagName("input");
    x= d.getAttribute("type");
    for (var i=0; i< d.length; i++){
        if (x[i] == "password")
            outputs++;
    }
    console.log("Number of Password Fields is: ", outputs);
}
   x= d.getAttribute("type");

您正在尝试从文档中获取类型属性。

你必须检查每个输入的 type 属性,你不能只得到一次并在任何地方重用它。

将 get 属性调用移到 for 循环内,并将其应用于元素对象。

我已经为您修复了它,请尝试以下操作:

function countPasswds() {
    var inputType;
    var outputs = 0;
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        inputType = inputs[i].getAttribute("type");
        if (inputType == "password")
            outputs++;
    }
    console.log("Number of Password Fields is: ", outputs);
}

您的函数存在许多问题。首先,不要使用一个字符变量名称,这会使您的代码非常难以阅读或理解。

您已经为 input 个元素的数量设置了 for 循环,但在循环内部,试图获取'i'-th x 的值。

修复的主要部分是将getAttribute函数移动到循环内。