当我点击按钮时,我有一个变量来捕捉屏幕的高度,但是下面的方法都没有得到空值。我不知道得到它的合适人选,有人可以帮助我吗?谢谢!
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function abc()
{
//method 1
var h = $("<%= hf_height.Value %>");
//method 2
var h = $("<%= hf_height.ClientID %>").val();
//method 3
var h = $("#height").val();
h = $(window).height();
}
</script>
<asp:Button ID="code_s_button" runat="server" Text="Search Code"
onclick="code_s_button_Click" onclientclick="abc()" />
<asp:HiddenField ID="hf_height" runat="server"/>
<input type="hidden" id="height"/>
//test both with runat="server" and no runat="server"
</Content>
protected void code_s_button_Click(object sender, EventArgs e)
{
hf_height.Value = ((HiddenField)Page.FindControl("height")).ToString(); // for method 3
Alert.Show(hf_height.Value);
}
答案 0 :(得分:2)
尝试以下代码(我已经测试过并且工作正常):
ASPX页面
<script type="text/javascript">
function abc() {
$("#<%=height.ClientID%>").val($(window).height());
}
</script>
<asp:Button ID="code_s_button" runat="server" Text="Search Code"
OnClick="code_s_button_Click" OnClientClick="abc()" />
<asp:HiddenField ID="hf_height" runat="server" />
<input type="hidden" id="height" runat="server" />
代码背后:
protected void code_s_button_Click(object sender, EventArgs e)
{
var height = this.height.Value;
}
注意:我在您的javascript代码中发现的错误是缺少'#'
答案 1 :(得分:0)
在javascript abc()
函数
var h = document.getElementById('<%=hf_height.ClientID %>').value;
h = $(window).height();
在您的代码中,您可以访问隐藏字段,如下所示
protected void code_s_button_Click(object sender, EventArgs e)
{
hf_height.Value = this.height.Value;
Alert.Show(hf_height.Value);
}