65.9K
CodeProject 正在变化。 阅读更多。
Home

点击/选择 ASP.NET GridView 或 HTML 5 表格中的行

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.84/5 (31投票s)

2011 年 6 月 10 日

CPOL

2分钟阅读

viewsIcon

280182

通过添加“onclick”事件和使用 JavaScript 和 CSS3 进行格式化,使整个表格行可点击/可选择。

引言

所建议的技术适用于 ASP.NET GridView 对象,以及本质上任何 HTML 表格的 tr 元素。首先,它通过添加 onclick 事件(参见 C# 中的列表 1)使整个 GridView 行对象(渲染为“tr”元素)“可点击”。相关的事件处理程序过程执行点击/选择的行的自定义格式化,使其与同一表格中的其他行在视觉上有所不同(有关实现此功能的 JavaScript 代码片段,请参见列表 2)。

演示

点击下面的图片以打开嵌入式 YouTube 视频播放器的功能演示,演示所建议的技术

YouTube Embedded Video

图 1. 演示快照显示,通过修改第一个单元格中的文本属性,已选择表格行对应于项目 6

列表 1:添加 onclick 事件(C# 代码隐藏文件)

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e){
    if (e.Row.RowType == DataControlRowType.DataRow){
        // javascript function to call on row-click event
        e.Row.Attributes.Add("onClick", "javascript:void SelectRow(this);");
    }
}

列表 2:将 JavaScript 函数添加到页面头部部分

<script type="text/javascript">
// format current row
function SelectRow(row) {
 var _selectColor = "#303030";
 var _normalColor = "#909090";
 var _selectFontSize = "3em";
 var _normalFontSize = "2em";
 // get all data rows - siblings to current
 var _rows = row.parentNode.childNodes;
 // deselect all data rows
 try {
     for (i = 0; i < _rows.length; i++) {
         var _firstCell = _rows[i].getElementsByTagName("td")[0];
         _firstCell.style.color = _normalColor;
         _firstCell.style.fontSize = _normalFontSize;
         _firstCell.style.fontWeight = "normal";
     }
 }
 catch (e) { }
 // select current row (formatting applied to first cell)
 var _selectedRowFirstCell = row.getElementsByTagName("td")[0];
 _selectedRowFirstCell.style.color = _selectColor;
 _selectedRowFirstCell.style.fontSize = _selectFontSize;
 _selectedRowFirstCell.style.fontWeight = "bold";
}
</script>

开发说明

注意 1:事件绑定也可以在客户端完成,例如使用 jQuery .click() 事件。出于主要是教学目的,这里使用 C# 和 DataRowBound 事件来实现,以与核心 .NET 技术集保持一致。

注意 2:为了在“页面加载”事件上选择/播放网格中的第一项,请使用下面显示的 jQuery 代码片段(它插入了一个小的延迟时间)

$(document).ready(function () { 
  // start the first item after small delay 
  setTimeout('PlayRowItem()', _initDelay); 
});

注意 3:正如评论中指出的那样,可以通过使用一对 addClass()removeClass() jQuery 方法来应用于选定的行视觉效果。通过 CSS3 和 jQuery 对行进行样式化,而不是像列表 2 所示那样通过 jQuery 直接修改元素属性,应该被认为是未来 Web 开发中更可取的方法,但请注意,在 jQuery 1.4.2 版本之前,这些方法存在一些缺陷(从该版本开始,并且持续到以后,这两种方法似乎在所有主要 Web 浏览器中都能很好地工作)。

额外资源

CodeProject 上的嵌入式 YouTube SDK:

  1. YouTube™ 嵌入式视频播放器:扩展 API (C#)[^]
© . All rights reserved.