您现在的位置是:网站首页> 编程资料编程资料
ASP.NET批量操作基于原生html标签的无序列表的三种方法_实用技巧_
2023-05-24
330人已围观
简介 ASP.NET批量操作基于原生html标签的无序列表的三种方法_实用技巧_
在网页开发中,经常要用到无序列表。事实上在符合W3C标准的div+css布局中,无序列表被大量使用,ASP.NET虽然内置了BulletedList控件,用于创建和操作无序列表,但感觉不太好用。本篇介绍服务器端ASP.NET批量操作基于原生html标签的无序列表的三种方法。
方法一,将li元素做成html控件,加上id,用FindControl方法。
aspx代码:
aspx.cs代码:
protected void Button1_Click(object sender, EventArgs e) { //单击按钮后批量改变li元素的内联文本值及样式 for (int i = 1; i <= 8; i++) { HtmlGenericControl li = this.FindControl("li" + i) as HtmlGenericControl; li.InnerHtml = "新值" + i.ToString(); li.Attributes.CssStyle.Value = "color:red"; } }方法二,将ul、li元素做成html控件,用ul控件的Controls集合遍历。
aspx代码:
aspx.cs代码:
private int counter = 1; protected void Button1_Click(object sender, EventArgs e) { //单击按钮后批量改变li元素的内联文本值及样式 foreach (Control control in ul1.Controls) { if (control is HtmlGenericControl) { HtmlGenericControl li = control as HtmlGenericControl; li.InnerHtml = "新值" + (counter++).ToString(); li.Attributes.CssStyle.Value = "color:red"; } } }方法三,利用HtmlAgilityPack,对元素以Dom方式操作。
aspx代码:
aspx.cs代码:
protected void Button1_Click(object sender, EventArgs e) { //单击按钮后批量改变li元素的内联文本值及样式 HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(ul1.InnerHtml); HtmlNodeCollection lis = htmlDoc.DocumentNode.SelectNodes("li"); for (int i = 0; i < lis.Count; i++) { lis[i].InnerHtml = "新值" + (i + 1).ToString(); lis[i].Attributes.Add("style", "color:red"); } ul1.InnerHtml = htmlDoc.DocumentNode.InnerHtml; }以上三种方法各有优缺点,可根据实际情况选用。
您可能感兴趣的文章:
相关内容
- ASP.NET中使用开源组件NPOI快速导入导出Execl数据_实用技巧_
- AspNetPager控件的最基本用法示例介绍_实用技巧_
- asp.net操作javascript:confirm返回值的两种方式_实用技巧_
- asp.net中IDataParameter调用存储过程的实现方法_实用技巧_
- asp.net网站防恶意刷新的Cookies与Session解决方法_实用技巧_
- 在asp.net中使用加密数据库联接字符串保证数据安全_实用技巧_
- ASP.Net中数据展示控件的嵌套使用示例_实用技巧_
- asp.net中控制反转的理解(文字+代码)_实用技巧_
- Asp.net导出Excel/Csv文本格式数据的方法_实用技巧_
- ASP.NET实现单点登陆(SSO)适用于多种情况_实用技巧_
