首页 > 解决方案 > 遍历节点列表,获取节点项的值的长度

问题描述

我正在尝试动态获取邮政编码并在长度为 5 时对其进行验证。

我使用 querySelectorAll 来获取页面上的 Zipcode 字段,以及我将在验证后使用的其他一些字段。

我遍历节点列表并将其传递给另一个函数,如果值是正确的长度,则事件监听器将在其中启动。

function GetZipCodeDetails() {

            var zipId = document.querySelectorAll("[id*='ZipCode']");
            var countyId = document.querySelectorAll("[id*='CountyId']");
            var stateId = document.querySelectorAll("[id*='StateId']");
            var phoneId = document.querySelectorAll("[id*='PhoneNumber']");

            for (var i = 0; i < zipId.length; i++) {
                if (zipId[i].length = 5)
                AssortedZipCodeFunctions(zipId[i], countyId[i], stateId[i], phoneId[i]);
            }
        }

        function AssortedZipCodeFunctions(zipId, countyId, stateId, phoneId) {
            //Runs auto-county/state function only when zipcode field is completed
            document.addEventListener("keyup", (e) => {
                if (zipId.value.length == 5) {
                    GetCountyAndStateFromIds(zipId, countyId, stateId, phoneId);
                } });
        }

上面列出的代码对我来说非常适合;我只是想把第二个函数移到第一个函数中,但我不知道怎么做。我只是坚持为什么我不能执行以下操作:

function GetZipCodeDetails() {

            var zipId = document.querySelectorAll("[id*='ZipCode']");
            var countyId = document.querySelectorAll("[id*='CountyId']");
            var stateId = document.querySelectorAll("[id*='StateId']");
            var phoneId = document.querySelectorAll("[id*='PhoneNumber']");

            for (var i = 0; i < zipId.length; i++) {
                document.addEventListener("keyup", (e) => {
                    if (zipId[i].value.length == 5) {
                        GetCountyAndStateFromIds(zipId[i], countyId[i], stateId[i], phoneId[i]);
                    }
                });
            }
        }

以上给出:“TypeError:无法读取 HTMLDocument 中未定义的属性‘值’。”

我发现 for 循环正在调用第二个函数,而不是等到 Zipcode 值为 5...所以发生的所有事情都是我将它传递给另一个函数?或者,也许我被困在如何获取节点项的值的长度上?请帮忙。

标签: javascriptnode.jsarraysecmascript-6nodes

解决方案


在您的事件侦听器中,您将它添加到文档而不是单独添加每个元素

for (var i = 0; i < zipId.length; i++) {
                zipId[I].addEventListener("keyup", (e) => {
                    if (zipId[i].value.length == 5) {
                        GetCountyAndStateFromIds(zipId[i], countyId[i], stateId[i], phoneId[i]);
                    }
                });
            }

推荐阅读