[英]Accessing global variables in JavaScript functions
I am using C# asp.net mvc3. 我正在使用C#asp.net mvc3。 In one of my views, say I declare a variable like this:
在我的一种观点中,假设我声明了一个这样的变量:
@{
ViewBag.Title = "title"
string mystr;
}
I need to set the value of the variable mystr in a function of the script. 我需要在脚本函数中设置变量mystr的值。 How do I access this variable from the script?
如何从脚本访问此变量? Suppose I have a function like
假设我有一个像
<Script type="text/javascript">
function(){
var st = "This string is for the global variable"
mystr = st;
}
</script>
mystr will later be used in the html code like this: <h2>@mystr</h2>
. mystr稍后将在html代码中使用,例如:
<h2>@mystr</h2>
。 Is there a similar way of accessing a variable from a function? 有没有从函数访问变量的类似方法?
mystr
in your example is server side variable that lives during cshtml
view parsing. 您的示例中的
mystr
是在cshtml
视图解析期间cshtml
服务器端变量。 So you can't affect it with JS code on the client side . 所以,你不能在客户端 JS代码产生影响。 You can try something like this:
您可以尝试如下操作:
<script type="text/javascript">
window.mystr = @(mystr); // Set value while server side processing.
function(){
var st = "This string is for the global variable"
window.mystr = st; // Get/Set value
}
</script>
And use global variable mystr
on client side wherever you need. 并使用全局变量
mystr
的客户端,无论你需要的。
If you need then set header's text via JS you can do it for example with jQuery: 如果需要,则可以通过JS设置标题文本,例如使用jQuery:
<h2 id="header"></h2>
JS: JS:
$('#header').text(window.mystr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.