asp:CheckBox的InputAttributes和LabelAttributes属性

本文介绍了ASP.NET中CheckBox控件的新特性:InputAttributes和LabelAttributes。通过这两个属性,可以为CheckBox及其Label添加自定义属性,如点击事件。文章还对比了使用Attributes与InputAttributes的区别。

CheckBox 控件新增加了两个属性:InputAttributesLabelAttributes 。利用这两个属性,可以很方便地为label和input标签添加自定义属性,而使用 Attributes 则是不能完成这2个任务的。举一个例子,页面中定义一个asp:CheckBox:

<asp:CheckBox ID="cbTest" Text="CheckBox" runat="server" />

在后台代码中使用Attributes属性为其添加onclick事件:

cbTest.Attributes.Add("onclick", "checkBoxClick(this)");

然后浏览该页面,查看页面代码:

<input id="cbTest" type="checkbox" name="cbTest" onclick="checkBoxClick(this);" /><label for="cbTest">CheckBox</label>

后台程序为checkbox添加了onclick事件,但是label的事件无法添加,这是就可以使用LabelAttributes属性,为label添加事件。

cbTest.InputAttributes.Add("onclick", "checkBoxClick(this)");
cbTest.LabelAttributes.Add("onclick", "checkBoxClick(this)");

再次浏览该页面,查看页面代码:

<input id="cbTest" type="checkbox" name="cbTest" onclick="checkBoxClick(this)" /><label for="cbTest" onclick="checkBoxClick(this)">CheckBox</label>

发现label也有了onclick事件。在上面的代码中,我们已经使用了InputAttributes属性为checkbox添加事件,这个属性在此时的效果和使用Attributes属性添加事件得到的结果是一样的。但是他们还是会有些不同。在一些复杂的程序中,asp.net在解析aspx页面的时候,会为checkbox添加额外的<span>标签,此时Attributes属性添加的onclick事件就会被添加到span中,二并非input中,所以在此时,我们需用InputAttributes这个属性为input添加事件。

 

 



 

 

 

转载于:https://www.cnblogs.com/minglz/archive/2011/12/12/2284491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值