关于在使用了母板的页面里使用ClientID的问题
遇到一个奇怪的问题:
js代码来找服务器端文本空件应该加上ClientID,但为什么我下面的语句不行呢?
function check1()
{
var obj1 = document.getElementById( " <%=TextBox1.ClientID%> ").value;
var obj2 = document.all( " <%=TextBox1.ClientID%> ").value;
var obj3 = document.getElementById( 'ctl00_ContentPlaceHolder2_TextBox1 ').value;
alert(obj1);
alert(obj2);
alert(obj3);
var v1 = obj3.value;
alert(v1);
}
obj1,obj2 都为null,只有obj3能取到值,这是为什么啊?
其中ctl00_ContentPlaceHolder2_TextBox1是TextBox1控件在转化以后生成HTML以后的ID,当然没有问题。
另外,是不是.ClientID 这样不能写在控件里啊,我这样写:
<asp:TextBox ID= "TextBox2 " runat= "server " onblur= "sum( <%=TextBox1.ClientID%> , <%=TextBox2.ClientID%> ) "> </asp:TextBox>
这样生成HTML根本就没转化过来,还请各位指点,,多谢!
------解决方案--------------------2005中好象没这个问题了呀
2003中的吧
我有个想法没有实践过,不过你可以试试
从控件开始找父一直到页
只要是实现了INamingContainer,加入控件的ID这样来构造clientid
<%@ Page Language= "C# " MasterPageFile= "~/MasterPage.master " Title= "Untitled Page " %>
<script runat= "server ">
private string ResponseWriteClientID(Control ctrl) {
string clientid = ctrl.ClientID;
while (!((ctrl = ctrl.Parent) is Page ))
{
if(ctrl is INamingContainer)
clientid = ctrl.ClientID + "_ " + clientid;
}
return clientid;
}
</script>
<asp:Content ID= "Content1 " ContentPlaceHolderID= "ContentPlaceHolder1 " Runat= "Server ">
<asp:TextBox runat= "server " ID= "tb " />
<br /> 客户端ID: <br /> <b> <%= ResponseWriteClientID(tb)%> <br /> </b>
<br /> 客户端ID: <br /> <b> <%= tb.ClientID%> <br /> </b>
</asp:Content>
你看看哪个在2003下是正确的,或者修改一下
模板页是默认的
<%@ Master Language= "C# " %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml " >
<head runat= "server ">
<title> Untitled Page </title>
</head>
<body>
<form id= "form1 " runat= "server ">
<div>
<asp:contentplaceholder id= "ContentPlaceHolder1 " runat= "server ">
</asp:contentplaceholder>
</div>
</form>
</body>
</html>
------解决方案--------------------在后台的时候传。
例如:
this.DropDownList1.Attributes.Add( "onChange ", "DistrictResult( " + this.DropDownList1.ClientID + ", " + this.DropDownList2.ClientID + ", "+ this.DropDownList3.ClientID + "); ");
------解决方案--------------------理论上应该是可以的,
你看看
var obj1 = document.getElementById( " <%=TextBox1.ClientID%> ")
生成的js脚本与页面上存在在这个控件的id是否一致