[英]this.id is empty for asp:CheckBox
I have an asp:CheckBox
with the following tag: 我有一个带有以下标签的
asp:CheckBox
:
<asp:CheckBox ID="cbTest1" runat="server" onchange="cbChange(this.id);"/>
cbChange
is a Javascript function in the <head>
that looks like this (it's simple for now): cbChange
是<head>
中的Javascript函数,看起来像这样(现在很简单):
<script type="text/javascript">
function cbChange(senderID) {
alert('|' + senderID + '|'); // '|' is to help see string length
return false;
}
</script>
Now, whenever I click on cbTest1
, I get the alert box with the following text: 现在,每当我单击
cbTest1
,都会出现带有以下文本的警报框:
||
||
In other words, it's an empty/null string. 换句话说,它是一个空/空字符串。 I should also note that when I use a more traditional
<input>
that I get the expected results: 我还应该注意,当我使用更传统的
<input>
,可以获得预期的结果:
(Code for <input>
) (
<input>
代码)
<input type="checkbox" name="cbtest2" id="cbtest2" onchange="cbChange(this.id);" />
(Text in alert box when I check cbtest2
) (当我检查
cbtest2
时,警告框中的文本)
|cbtest2|
| cbtest2 |
Why would I be getting the null/empty string with the asp:Checkbox
, but expected behaviour with the <input>
? 为什么我要使用
asp:Checkbox
获取null / empty字符串,但为什么要使用<input>
预期的行为?
EDIT I did a little bit more research, since the asp:CheckBox
has the ID
attribute instead of (lowercase) id
, so I tried onchange="cbChange(this.ID);"
编辑我做了更多的研究,因为
asp:CheckBox
具有ID
属性而不是(小写) id
,所以我尝试了onchange="cbChange(this.ID);"
. 。 Now I get the following output in the alert box:
现在,我在警报框中得到以下输出:
|undefined|
|未定义|
Why would this also be happening? 为什么还会发生这种情况?
Pull up your rendered page source, you'll see the ASP actually renders this as: 拉起渲染的页面源,您将看到ASP实际将其渲染为:
<span onchange="cbChange(this.id);"><input id="ContentArea_cbTest" type="checkbox" name="ctl00$ContentArea$cbTest" /></span>
Your input
element is actually nested with a span
element. 您的
input
元素实际上嵌套了一个span
元素。
Using Pure JS, you can still get the ID of your input
by doing: 使用Pure JS,您仍然可以通过执行以下操作获取
input
的ID:
<asp:CheckBox ID="cbTest" runat="server" onchange="cbChange(this.childNodes[0].id);"/>
If you view source, you'll see: 如果您查看源代码,则会看到:
<span onchange="cbChange(this.id);">
<input id="cbTest" type="checkbox" name="cbTest" />
</span>
One of the downsides of WebForms - the markup doesn't always come as you'd expect. WebForms的缺点之一-标记并非总是如您所愿。
Your best bet is to hook up the event manually on the client. 最好的选择是在客户端上手动挂接事件。 If you happen to be using jQuery, you can do:
如果碰巧正在使用jQuery,则可以执行以下操作:
jQuery(document).ready(function() {
jQuery("#<%= cbTest.ClientID %>").click(function() {
cbChange(jQuery(this).attr("id"));
});
});
(If you're not using jQuery, do the same thing, just hook up to the click event manually using regular javascript - I always have to look up that syntax though...) (如果您不使用jQuery,请执行相同的操作,只需使用常规javascript手动连接到click事件-尽管我始终必须查找该语法...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.