开发环境: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/