将值从代码隐藏传递到Javascript
本文关键字:Javascript 隐藏 代码 | 更新日期: 2023-09-27 17:50:13
我使用jQueryUI ProgressBar向用户显示他们使用了多少允许的文件存储空间。该百分比在代码隐藏中计算,并应传递给Javascript。
<<p> Aspx代码/strong> <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript">
$(function () {
var pct = document.getElementById("filesPercentage").value;
$("#progressbar").progressbar({
value: pct
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
...
<input type="hidden" runat="server" id="filesPercentage" />
<div id="progressbar"></div>
...
</asp:Content>
代码后面
protected void Page_Load(object sender, EventArgs e)
{
filesPercentage.Value = "85";
}
似乎无法从隐藏字段中获取百分比数字。
您需要获取隐藏输入
的呈现idvar pct = document.getElementById("<%=filesPercentage.ClientID%>").value;
并且从您在服务器上运行输入的那一刻起,最好使用asp:HiddenField
而不是input
因为你的隐藏字段是一个服务器控件,它可能是ID正在生成的东西,而不是filesPercentage
(可能像ctl00_ctl00_filesPercentage
)
- 你可能需要将生成的客户端ID应用到你的javascript
- 或使用其他方式选择隐藏值,如
$('[hidden's parent element] input[type="hidden"]').val()
document.getElementById("<%=filesPercentage.ClientID%>").value;
另外,看起来进度条值正在等待一个数字,所以您可能需要执行value: pct * 1
或value: parseInt(pct)
试试这个
var pct = document.getElementById("<%=filesPercentage.ClientID %>").value;
.net将修改您给控件的id,以确保它是唯一的,因此您不能使用正确的id访问它。如果您给隐藏字段一个唯一的类名,您可以这样访问该值:
<input type="hidden" runat="server" id="filesPercentage" class="hiddenClass" />
var pct = $('.hiddenClass').val();
这样比较干净:-)
$("#progressbar").progressbar({
value: $("#<%=filesPercentage.ClientID%>").val()
});