为什么当我记录特定节点列表中所有节点的tagName
时,它会给我重复的undefined
反馈?
这是我从以下代码中提取节点的代码的一部分:
的index.html
<form name="contactForm" id="contactForm">
<div id="textInfo">
<ul>
<li>
<label for="firstName" class="mainLabel">First Name : </label>
<input type="text" name="firstName" id="firstName"/>
<span>This must be filled</span>
</li>
<li>
<label for="lastName" class="mainLabel">Last Name : </label>
<input type="text" name="lastName" id="lastName"></input>
<span>This must be filled</span>
</li>
<li>
<label for="email" class="mainLabel">E-mail : </label>
<input type="email" name="email" id="email"></input>
<span>This must be filled</span>
</li>
</ul>
</div>
的script.js
var myForm = document.forms["contactForm"];
eventUtil.add(myForm, "submit" , function(evt){
var firstName = myForm.elements["firstName"];
if(firstName.value == ""){
for(i=0; i < firstName.parentNode.childNodes.length ; i++){
console.log("childNodes[" + i + "]: " + firstName.parentNode.childNodes[i].tagName);
}
eventUtil.preventDefault(evt);
}
});
,输出为:
childNodes[0]: undefined
childNodes[1]: LABEL
childNodes[2]: undefined
childNodes[3]: INPUT
childNodes[4]: undefined
childNodes[5]: SPAN
childNodes[6]: undefined
为什么它会反复给我undefined
输出?
答案 0 :(得分:0)
for(i=0; i < firstName.parentNode.childNodes.length ; i++){
var currNode=firstName.parentNode.childNodes[i];
if(currNode.nodeType==1){
console.log("childNodes[" + i + "]: " + currNode.tagName);
}
}
您可以检查nodeType(Node.ELEMENT_NODE == 1)以选择仅元素。