[英]How to create a global variable that can be accessed from external javascript as well as asp.net website
在我的网站上,我们有一个通用的javascript,我们将为变量赋值,我想在aspx页面以及另一个javascript文件中调用该变量,有人可以让我知道如何在全局范围内声明这种varibale。
you can write a common javascript file which will contain all the global variable(assuming they are constant and they wont change). 您可以编写一个通用的javascript文件,其中将包含所有全局变量(假设它们是常量,并且不会改变)。
if you have the variable value as non constant, there is noway that you can put it in a javascript file, instead you can use the local storage, cookies to store the information and use it across your javascript files. 如果您将变量值设为非常量,则绝对不能将其放在javascript文件中,而可以使用本地存储,cookie来存储信息并在整个javascript文件中使用它。
the life time of a javascript variable is limited to the page, you navigate to other page its lost. javascript变量的生命周期仅限于该页面,您导航到其丢失的其他页面。
If you do not expect any page to assign new values in your common javascript, you can add it to the page as the first header script : 如果您不希望任何页面在通用javascript中分配新值,则可以将其作为第一个标头脚本添加到页面中:
<script type="text/javascript" src="script/common.js"></script>
If you want to assign new values and reuse them, it is possible if you let ASP.Net generate your javascript file by passing a query string to the next page's URL, then in that page's script tag. 如果要分配新值并重复使用它们,则可以让ASP.Net通过将查询字符串传递到下一页的URL,然后传递到该页面的script标记中来生成javascript文件。 Let's assume that your common variable is called "myGlobalVar".
假设您的公用变量称为“ myGlobalVar”。 Supposing that "common_js.aspx" dynamically generates your variable definition, you can have something like this :
假设“ common_js.aspx”动态生成您的变量定义,则可以有如下所示:
(URL : www.mysite.com/products.aspx?myGlobalVar=3) (网址:www.mysite.com/products.aspx?myGlobalVar=3)
<script type="text/javascript" src="script/common_js.aspx?myGlobalVar=3"></script>
This will keep track of your new js value whenever an update has to be made. 每当需要进行更新时,这都会跟踪您的新js值。
But if so, you may likely want to use a cleaner way to achieve what you want, for example : using the context manager instead of common js vars. 但是,如果是这样,您可能想使用一种更简洁的方法来实现所需的功能,例如:使用上下文管理器而不是普通的js vars。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.