【发布时间】:2016-05-03 09:18:14
【问题描述】:
HTML
<input id="TextBox" type="text" runat="server" readonly="readonly" />
JS
function MyFunct(sender, args) {
var TextBox = document.getElementById('<%= TextBox.ClientID %>');
if (true) {
TextBox.value = "somevalue";
TextBox.setAttribute('readonly', 'readonly');
$('#<%= TextBox.ClientID %>').addClass("disabledTb");
}
else {
TextBox.value = "";
TextBox.readOnly = false;
$('#<%= TextBox.ClientID %>').removeClass("disabledTb");
}
}
CSS
.disabledTb {
background-color: rgb(235, 235, 228);
color: rgb(84, 84, 84);
}
只读属性正在工作,我不得不将输入从 asp:TextBox 更改为标准 HTML textobx,因为否则该值不会被检索到服务器端并且我不想使用隐藏字段。
但是,现在不再应用 .disabledTb 类。其余代码工作正常,并且正在更改
var TextBox = document.getElementById('<%= TextBox.ClientID %>');
到
var TextBox = document.getElementById('#<%= TextBox.ClientID %>');
导致控制台中出现空引用
更新
我忘了说我使用的是母版页,所以 id 最终类似于 'ctl00$ContentPlaceHolder1$TextBox'
解决方案
原来我引用了错误的控件。解决了我的问题。 其余代码完全可用。
jQuery 函数需要在调用 ID 时使用 # 引用控件,而不是纯 Javascript。 <%= TextBox.ClientID %> 甚至适用于将 runat 属性设置为 server 的 HTML 输入。这将在使用母版页时提供正确的 ID。
【问题讨论】:
标签: javascript c# jquery html asp.net