我在使用隐藏字段和 jQuery 将 div 的物理大小(高度和宽度)传递到 ASP.NET 变量时遇到问题。
这是我的代码,但它不起作用:
$("<%=hfAdvertHeight.ClientID %>").val($("#Advert_Container").attr("height"));
有任何想法吗?
非常感谢。
如果你的 ASP.NET 隐藏字段 ID 是“HiddenMyField”,那么使用这个:
<asp:HiddenField ID="HiddenMyField" runat="server" />
var input = $("[id$='HiddenMyField']").val();
$.ajax {
url:.....,
data: JSON.stringify(input),
...
}
这对我来说很好。
在您的 html 中添加 "ClientIDMode="Static"" 作为隐藏控件属性,然后尝试: $("#hfAdvertHeight").val($("#Advert_Container").attr("height"));
代码应包含 id 选择器#
$("#<%=hfAdvertHeight.ClientID %>").val($("#Advert_Container").attr("height"));
如果您在页面加载时执行此操作,请确保将代码包装在ready
函数中。
$(document).ready(function(){
$("#<%=hfAdvertHeight.ClientID %>").val($("#Advert_Container").height());
});
另请注意,attr
可以使用更轻松地检索而不是通过它检索高度属性.height()
。
您忘记了隐藏字段名称前的 #:
$("#<%=hfAdvertHeight.ClientID %>").val($("#Advert_Container").attr("height"));