Javascript 未定义为$(“inputElement”).val()
我在asp.net项目的母版页中有此代码Javascript 未定义为$(“inputElement”).val(),javascript,asp.net,ajax,Javascript,Asp.net,Ajax,我在asp.net项目的母版页中有此代码 <div style="display:none"> <input id="txtPageIDMaster" name="txtPageIDMaster" type="text" value="0" runat="server"/> <input id="txtOnLineUserMaster" type="text" value="0" runat="server"/> </div
<div style="display:none">
<input id="txtPageIDMaster" name="txtPageIDMaster" type="text" value="0" runat="server"/>
<input id="txtOnLineUserMaster" type="text" value="0" runat="server"/>
</div>
但请告诉我:未定义的应该可以:
alert($("<%= txtPageIDMaster.ClientID %>").val())
警报($(“”).val()
为什么??因为asp.net为控件设置了自己的id。因此,属性为您提供生成的ID
从ASP.NET 4开始,这现在基于属性。它可以是四个值:
ClientIDMode.Inherit
(这是默认值,也是.NET4之前的默认值)ClientIDMode.AutoID
clientdmode.Preditable
(当html ID设置为asp.net ID属性时)ClientIDMode.Static
Asp.net MVC不会这样做。您可以完全控制html,您的ID永远不会自动生成。试试这个
alert(document.getElementById('txtPageIDMaster').value);
从jQuery的角度来看:
$(function(){
alert($("#txtPageIDMaster").val());//adapted for ASP.net as per gideon's suggestion, I expect
};)
正如您所提到的runat=server,该控件将被视为服务器端控件,因此在javascript中找到它时,您需要指定controlname.clientID,因此您需要在javascript中提到如下内容
alert(document.getElementById('<%= txtPageIDMaster.ClientID %>').value);
警报(document.getElementById(“”).value);
感谢您的精彩描述,但这行代码在我的上下文中不起作用@user1129318(1)
你是在使用asp.net->web表单还是**asp.net-mvc**,(2)
当页面在Chrome中呈现时,你能检查你的元素,看看它的ID是什么吗(3)
您还可以检查您的浏览器控制台是否存在任何其他错误吗?我很早就测试了这一行,但没有定义。请再试一次,因为它可以在任何平台上工作。不要用MVC标记asp.net web窗体控件
alert(document.getElementById('<%= txtPageIDMaster.ClientID %>').value);