您的位置:首页 > Web前端 > JavaScript

外部JS得到客户端ID

2010-05-23 11:30 134 查看
大家都知道ASP.NET为了区分控件 HTML标签客户端ID与服务器ID在某些情况下是不同的

例如 使用了模板页
假如有个服务器TextBox ID为txtName
那么客户端ID可能会是ctl00_ContentPlaceHolder1_txtName

当写JScript代码时,想得到某控件
如果JScript代码直接写在本页时 可以用如下代码获得:




Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>无标题页</title>
<script language="javascript" type="text/javascript">
function GetValue(){
var txtNameValue=$id("<%=txtName.ClientID %>").value;
alert(txtNameValue);
}
function $id(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
<form id="form1" runat="server" style="">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input type="button" value="查看" onclick="GetValue()" />
</form>
</body>
</html>

当JScript写在单独的Js文件中 这种方法就不行了
可以用如下方式解决
首先在页面定义一个函数(这个函数相当于OOP中的类)
例如:




Default2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>无标题页</title>
</head>
<body>
<form id="form1" runat="server" style="">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input type="button" value="查看" onclick="GetValue()" />
</form>
<script type="text/javascript">
function IdList()
{
this.txtShopName="<%= txtName.ClientID %>";
//




}
</script>
<script src="js/test.js" language="javascript" type="text/javascript" ></script>
</body>
</html>

外部JScript文件

然后在JScript文件中实例化这个“类” 例如:




test.js
//关联Default2.aspx
function GetValue(){
var idList=new IdList();
alert($id(idList.txtShopName).value);
}
//简化document.getElementById
function $id(id) {
return document.getElementById(id);
}

如上方法就可解决外部JScript不能得到正确的客户端ID了

为了便于理解 最好在JScript文件中标注 与那个页面关联

http://www.e5-zone.com/shopRegister.html 该页面使用了此方法 提供出来 以便大家参考
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: