为什么gridview行的颜色没有改变?
本文关键字:改变 颜色 gridview 为什么 | 更新日期: 2023-09-27 18:13:38
当我点击gridview的一行时,我希望它的颜色改变。在c#中,我有以下代码:
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
e.Row.Attributes.Add("onclick", "ChangeRowColor('"+e.Row.ClientID +" ')");
}
JavaScript中是这样的:
<script type="text/javascript">
function ChangeRowColor(row) {
//change the color of the current row to light yellow
document.getElementById(row).style.backgroundColor = "#ffffda";
}
</script>
我检查了发送给JavaScript的gridview行的id是true,但该行的颜色没有改变!我怎样才能做到呢?
检查TD
的背景样式。最好使用类而不是内联,以便TD
可以继承和更改:
<style>
tr.clicked {background-color: ffffda;}
tr.clicked td{ background: #fffda; }
</style>
function ChangeRowColor(row) {
document.getElementById(row).className= "clicked";
}
你可以这样做
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes.Add("onclick", "this.style.backgroundColor='#ffffda'");
}
所有这些都是很好的答案,但我要做的(因为你无论如何都在使用javascript)是"jquery"这到最大:p
在头部包含jquery脚本文件:
<script src="local path or cdn path"></script>
然后在你的表行上使用某种类型的标识符(在这个例子中使用类名,因为你正在使用GridView控件)
<RowStyle CssClass="rowstyle bg-changer" />
<AlternativeRowStyle CssClass="altrowstyle bg-changer" />
然后你可以创建你的jQuery函数来管理背景颜色的变化
$(function(){
$('.bg-changer').click(function(){
$(this).addClass('selected');
});
});
在你的样式表中,你可以很好地控制.bg-changer
, .bg-changer .selected
和你的两行样式rowstyle
和altrowstyle
,例如
.rowstyle .selected{ background: red; }
.altrowstyle .selected{ background: blue; }
如果你想更进一步,你可以切换所选的类
$(this).toggleClass('selected');
可以选择和取消选择一行
更改为使用jQuery:
更新感谢@ocanals评论。(注意包含"#"+)
<script type="text/javascript">
function ChangeRowColor(row) {
$("#"+row).css("backgroundColor","#ffffda");
}
</script>