表单元素遍历
分别使用ASP.NET和Javascript遍历表单元素,总结了几种方法,如下:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<script type="text/javascript">
function load()
{
//遍历Img
var imgs = document.images;
for(var i=0;i<imgs.length;i++)
{
imgs[i].src="http://images.cnblogs.com/logo.gif"
}
//遍历button
var control=document.form1.elements;
for(var i=0;i<control.length;i++)
{
if(control[i].type=="submit")
control[i].value="ok,点吧!"
}
//遍历checkbox
var rbcontrol= document.getElementsByTagName("input");
for(var i=0;i<rbcontrol.length;i++)
{
if(rbcontrol[i].type=='radio')
{
rbcontrol[i].checked=true;
}
}
}
</script>
</head>
<body onload="load()">
<form id="form1" runat="server">
<div>
<p><label>.NET遍历</label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</p>
<p> <label>.NET遍历</label>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" />
<asp:CheckBox ID="CheckBox4" runat="server" />
</p>
<p><label>javascript遍历</label>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Button ID="Button3" runat="server" Text="Button" />
<asp:Button ID="Button4" runat="server" Text="Button" />
<asp:Button ID="Button5" runat="server" Text="Button" />
</p>
<p><label>javascript遍历</label>
<asp:Image ID="Image1" runat="server" />
<asp:Image ID="Image2" runat="server" />
<asp:Image ID="Image3" runat="server" />
</p>
<p><label>javascript遍历</label>
<asp:RadioButton ID="RadioButton1" runat="server" />
<asp:RadioButton ID="RadioButton2" runat="server" />
<asp:RadioButton ID="RadioButton3" runat="server" />
</p>
</div>
</form>
</body>
</html>
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
getTextBox();
getCheckBox();
}
private void getTextBox()
{
for (int i = 0; i < this.Page.Form.Controls.Count; i++)
{
if (this.Page.Form.Controls[i].GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
{
TextBox tb = (TextBox)this.Page.Form.Controls[i];
tb.Text = "我是TextBox";
}
}
}
private void getCheckBox()
{
foreach (System.Web.UI.Control control in form1.Controls)
{
if (control.GetType().ToString().Equals("System.Web.UI.WebControls.CheckBox"))
{
CheckBox cb = (CheckBox)control;
cb.Checked = true;
}
}
}
}
效果: