如何在回发时保留 JavaScript 函数中的静态变量值?
我有下面的示例:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<script type="text/javascript">
function test(){
if (test.initialized=='undefined'){
test.initialized = 'true';
}
alert(test.initialized);
};
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Button ID="btnPostBack" runat="server" Text="Post back" OnClientClick="test()" />
</asp:Content>
当我单击页面上的回发时,我发现初始化的变量(在函数本身上定义)正在丢失其值并再次变为“未定义”。
是否可以在定义这些静态值后保留这些值并使它们不受页面上任何回发的影响?
I have this sample below:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<script type="text/javascript">
function test(){
if (test.initialized=='undefined'){
test.initialized = 'true';
}
alert(test.initialized);
};
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Button ID="btnPostBack" runat="server" Text="Post back" OnClientClick="test()" />
</asp:Content>
When I click post-back on the page, I found out that the variable initialized -which is defined on the function itself- is loosing its value and becoming 'undefined' again.
Is it possible to keep those static values once they are defined and make them unaffected from any post backs on the page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当页面重新加载时,javascript 将在回发时重新执行(除非您使用更新面板)。
要保留客户端值,请使用 JS 将值写入 asp 隐藏字段,并且如果 IsPostBack 为 true,则不渲染 javascript,这样它就不会在回发时被覆盖
javascript is going to be re-executed on postback as the page reloads (unless you are using update panels).
to preserve a client side value, write the value into an asp hidden field using JS, and don't render the javascript if IsPostBack is true so that it doesn't get overwritten on postback
我认为使用部分回发也是一种方法。
如果不可能,只能使用Java脚本,我认为cookies可以是另一种方式,只要用户不关闭它们。
我的感觉是最好的方法是以我不需要存储它的方式设计页面:)
I think using partial-post back is a way as well.
If it is not possible, only by using Java script I think cookies can be another way as long as they are not turned of by the user.
My feeling is the best way is to design the page in a way that I would not need to store it :)
您可以添加一个隐藏字段并设置其值吗?我认为这样它将保留在视图状态中,并且您可以使用以下命令将其值加载回变量中:
var p = '<%=blah.Text%>';
You could add a hidden field and set the value of this? I think this way it'll be preserved in the viewstate, and you can load its value back into your variable with something like:
var p = '<%=blah.Text%>';
您可以将它们添加为查询字符串或将它们保存在 cookie 中。
You could add them as a query string or keep them in a cookie.
也许你想做这样的事情。我还认为您将测试函数与测试对象混淆了。
Maybe you want to do something like this. I also think that you are confusing test function with test object.