我有这个简单的代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<script>
$(document).ready(function () {
var username = $("#txtusername").val();
$("#btnsubmit").click(function () {
alert(username);
});
})
</script>
<asp:Label ID="lblusername" Text="User Name:" runat="server"></asp:Label>
<asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
<asp:Label ID="lblpass" Text="Password:" runat="server"></asp:Label>
<asp:TextBox ID="txtpass" runat="server"></asp:TextBox>
<asp:Button ID="btnsubmit" Text="Submit" runat="server" />
</div>
</form>
</body>
</html>
当我在浏览器中运行它时,为文本框提供值并单击按钮它会提醒空白。当下次点击时显示该值。可能是什么问题。?
第二次尝试。
答案 0 :(得分:1)
那是因为你正在读取事件处理程序之外的值。基本上,您希望在用户单击提交按钮时读取文本框的值,而不是在它之前。
可写如下:
$(document).ready(function() {
// This code is executed when the page loads.
$("#btnsubmit").click(function() {
// This code is executed when the user clicks on the submit button.
var username = $("#txtusername").val();
alert(username);
});
})
答案 1 :(得分:1)
试试这个。在click函数中定义变量。否则输入框的初始值为空
$(document).ready(function() {
var username = $("#txtusername").val();
console.log('for initial input='+username) //initial value
$("#btnsubmit").click(function() {
var username = $("#txtusername").val();
console.log('after click input='+username) //after
});
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtusername">
<button id="btnsubmit">click</button>
&#13;