我需要能够遍历指定DIV标记内的所有表单域。基本上,任何给定的DIV标签都可以有多个表单域(这很容易解析),但它也可以包含任意数量的表,甚至额外的DIV标签(增加额外的层次分层)。遍历指定DIV标记内的所有表单域
我已经写了一个基本函数,通过父节点的每个直接后代(在这种情况下,DIV标记),并清除它的值。这部分工作正常。问题在于,如果孩子(孙辈)属于自己的孩子,那就解决孩子的问题。它卷起了无限循环。
在这种情况下,我需要能够找到DIV标签“panSomePanel”中的所有表单字段,其中将包括一些直接子项(txtTextField1),但也包括嵌套的TABLE对象和/或嵌套的DIV中的一些孙子标签(radRadioButton,DESC_txtTextArea)。
下面是一个简单的DIV及其内容:
<DIV id="panSomePanel">
<INPUT name="txtTextField1" type="text" id="txtTextField1" size="10"/><BR><BR>
<TABLE id="tblRadioButtons" border="0">
<TR>
<TD>
<INPUT id="radRadioButton_0" type="radio" name="radRadioButton" value="1" /><LABEL for="radRadioButton_0">Value 1</LABEL>
</TD>
<TD>
<INPUT id="radRadioButton_5" type="radio" name="radRadioButton" value="23" /><LABEL for="radRadioButton_5">Value 23</LABEL>
</TD>
</TR>
<TR>
<TD>
<INPUT id="radRadioButton_1" type="radio" name="radRadioButton" value="2" /><LABEL for="radRadioButton_1">Value 2</LABEL>
</TD>
<TD>
<INPUT id="radRadioButton_6" type="radio" name="radRadioButton" value="24" /><LABEL for="radRadioButton_6">Value 24</LABEL>
</TD>
</TR>
<TR>
<TD>
<INPUT id="radRadioButton_2" type="radio" name="radRadioButton" value="3" /><LABEL for="radRadioButton_2">Value 3</LABEL>
</TD>
<TD>
<INPUT id="radRadioButton_7" type="radio" name="radRadioButton" value="25" /><LABEL for="radRadioButton_7">Value 25</LABEL>
</TD>
</TR>
<TR>
<TD>
<INPUT id="radRadioButton_3" type="radio" name="radRadioButton" value="21" /><LABEL for="radRadioButton_3">Value 21</LABEL>
</TD>
<TD>
<INPUT id="radRadioButton_8" type="radio" name="radRadioButton" value="4" /><LABEL for="radRadioButton_8">Value 4</LABEL>
</TD>
</TR>
<TR>
<TD>
<INPUT id="radRadioButton_4" type="radio" name="radRadioButton" value="22" /><LABEL for="radRadioButton_4">Value 22</LABEL>
</TD>
</TR>
</TABLE>
<DIV id="panAnotherPanel"><BR>
<TABLE cellpadding="0" cellspacing="0" border="0" style="display:inline;vertical-align:top;">
<TR>
<TD valign="top">
<TEXTAREA name="DESC:txtTextArea" rows="3" cols="48" id="DESC_txtTextArea"></TEXTAREA>
</TD>
<TD valign="top"><SPAN id="DESC_lblCharCount" style="font-size:8pt;"></SPAN>
</TD>
</TR>
</TABLE>
</DIV>
</DIV>
这里是我写的函数:
function clearChildren(node) {
var child;
if (node.childNodes.length > 0) {
child= node.firstChild;
}
while(child) {
if (child.type == "text") {
alert(child.id);
child.value = "";
}
else if (child.type == "checkbox") {
child.checked = false;
}
else if (child.type == "radio") {
alert(child.id);
child.checked = false;
}
else if (child.type == "textarea") {
child.innerText = "";
}
//alert(child.childNodes.length);
if (child.childNodes.length > 0) {
var grandchild = child.firstChild;
while (grandchild) {
clearChildren(grandchild);
}
grandchild = grandchild.nextSibling;
}
child = child.nextSibling;
}
}
这个答案就派上了用场:-) – Erik 2010-06-05 23:20:17
虽然我应该注意的是.localName一个XML属性只出现这种情况的工作在HTML上的Firefox。改用.nodeName(然后知道标签全部大写) – Erik 2010-06-06 00:04:00