javascript - 遍历节点列表,获取节点项的值的长度
问题描述
我正在尝试动态获取邮政编码并在长度为 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...所以发生的所有事情都是我将它传递给另一个函数?或者,也许我被困在如何获取节点项的值的长度上?请帮忙。
解决方案
在您的事件侦听器中,您将它添加到文档而不是单独添加每个元素
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]);
}
});
}
推荐阅读
- python - 我可以根据 python 数据框中的相同列值更新列的值吗?
- c# - 如何制作“webhook”?
- javascript - MomentJS/Date 对象默认 UTC
- flask - jinja2 在烧瓶 wt-form 上循环
- r - ggplot如何在x和y坐标中放置标题
- jenkins-pipeline - 有什么方法可以在不使用额外插件的情况下将变量从 bash 脚本传递到 Jenkinsfile
- keycloak - 当 keycloak 保护的容器副本高于 1 时,错误重定向过多
- python - 在没有 One Hot 编码的情况下将分类数据转换为数值数据
- python-3.x - 在列表中重新搜索
- c++ - 如何使用 c++ 在 socket.io 中接收数据