[英]Why this function stops to work with other “get element” methods than getElementsByTagName?
i'm trying to adapt this JS form steps for my own: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps我正在尝试为自己调整此 JS 表单步骤: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps
There is a function that validates it:有一个 function 可以验证它:
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
But I want it to work only for specific field, so I added ID to the input and change the code to:但我希望它只适用于特定字段,所以我在输入中添加了 ID 并将代码更改为:
y = x[currentTab].getElementById("test");
But then it stops to work and console shows that x[currentTab] is not a function.但随后它停止工作,控制台显示 x[currentTab] 不是 function。 Please explain me, why this function works with
y = x[currentTab].getElementsByTagName("input");
请解释一下,为什么这个 function 与
y = x[currentTab].getElementsByTagName("input");
but stops if I change it for ID, class or name.但如果我将其更改为 ID、class 或名称,则会停止。
It's because getElementById
returns a single element instead of a NodeList
.这是因为
getElementById
返回单个元素而不是NodeList
。 Therefore, y[i]
no-longer works.因此,
y[i]
不再有效。 You can remove the whole loop part because there's only one.您可以删除整个循环部分,因为只有一个。
function validateForm() {
// This function deals with validation of the form fields
let valid = true;
const tabs = document.getElementsByClassName("tab"); // Do you need this?
const input = document.getElementById("test");
// A loop that checks every input field in the current tab:
if (input.value == "") {
// add an "invalid" class to the field:
input.className += " invalid";
// and set the current valid status to false
valid = false;
}
// ...
}
It should be noted that an element's ID must be unique document-wide so selecting by ID within a specific parent element doesn't make much sense.应该注意的是,元素的 ID 在文档范围内必须是唯一的,因此在特定父元素中按 ID 进行选择没有多大意义。 If each tab has an element with an ID of
test
, the HTML is invalid.如果每个选项卡都有一个 ID 为
test
的元素,则 HTML 无效。 You can still select a single element by class name with something like tabs[currentTab].querySelector('.test');
您仍然可以select使用类似
tabs[currentTab].querySelector('.test');
instead.反而。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.