javascript - 为什么单选按钮没有传递 asp 控件的 clientID

标签 javascript c# jquery asp.net webforms

开发环境:VS 2012

设计师代码
场景 1:使用 runat="server"(这是必需的),javascript 函数不起作用

<asp:TextBox ID="txtCost" runat="server"  ReadOnly="true" Text="250/-"></asp:TextBox>  


 <input type="radio"  name="myRadios" runat="server"  id="rb1" checked="true" onchange="javascript:UpdateClick(this,'<%=txtCost.ClientID %>');" value="1" /> Monthly
        <input type="radio"  name="myRadios" runat="server"  id="rb2" value="2" onchange="javascript:UpdateClick(this,'<%=txtCost.ClientID%>');" /> Weekly    

场景 2:runat="server"已删除(这是必需的),javascript 函数正常工作。

<asp:TextBox ID="txtCost" runat="server"  ReadOnly="true" Text="250/-"></asp:TextBox>  


 <input type="radio"  name="myRadios"   id="rb1" checked="true" onchange="javascript:UpdateClick(this,'<%=txtCost.ClientID %>');" value="1" /> Monthly
        <input type="radio"  name="myRadios"   id="rb2" value="2" onchange="javascript:UpdateClick(this,'<%=txtCost.ClientID%>');" /> Weekly  

Javascript 函数:

function UpdateClick(myRadio, ClientID) {

        currentValue = myRadio.value;
        if (currentValue == '1') {
            var txtCostBox = document.getElementById(ClientID);
            txtCostBox.value = '250/-';
        }
        else {
            var txtCostBox = document.getElementById(ClientID);
            txtCostBox.value = '600/-';

        }
        return false;
    }  

问题:

因此,当我在单选按钮中删除 runat="server"时,代码可以正常工作,而当我保留 runat="server"时,我得到的不是实际的客户端 ID,而是客户端 ID:

'<%=txtCost.ClientID%>'  

我有一个要求,我需要用 runat="server"保留单选按钮,你能告诉我如何解决上述问题吗?

最佳答案

您可以放置​​ onclick在你的代码后面,在 Page_Load .

rb1.Attributes["onclick"] = "javascript:UpdateClick(this,'" + txtCost.ClientID + "')";
rb2.Attributes["onclick"] = "javascript:UpdateClick(this,'" + txtCost.ClientID + "');"

此外,尝试更改 "<%=txtCost.ClientID %>"至:"<%# txtCost.ClientID %>" .

还有其他一些方法可以做到这一点。您还可以更改代码:

function UpdateClick(myRadio) {

   var textObj = document.getElemmentById("<%# txtCost.ClientID %>");
   ...
}

关于javascript - 为什么单选按钮没有传递 asp 控件的 clientID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436329/

相关文章:

javascript - 当 WebKit WebApp 为 "terminated"时会触发什么事件

javascript - 需要自定义模块的问题

c# - 为什么在使用 Microsoft.Bcl 时不能在我的 Windows Phone 7.1 MvvmCross 项目中使用 await 关键字 - 不能等待 'System.Threading.Tasks.Task?

jquery - 使用 CoffeeScript 更改特定元素中的类

jquery - Twitter Bootstrap - 在页面选项卡之间丢失淡入淡出类

jquery - 文本区域最大长度检查

javascript - 悬停标记时能够滚动 map 吗?

c# - Struct 隐式默认构造函数与无参数构造函数

c# - Linq-to-Sql 删除命令不起作用

jquery - ToBootstrap 与容器宽度对齐