javascript 在多个 <script> 块中共享 JS 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5781197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sharing JS variables in multiple <script> blocks
提问by cabaret
I'm working on a CodeIgniter application.
我正在开发 CodeIgniter 应用程序。
I have a view, let's call it Calendar, which has a JS/jQuery <script>
block in it. Looks like this:
我有一个视图,我们称之为日历,其中有一个 JS/jQuery<script>
块。看起来像这样:
$(document).ready(function() {
$("#day_list").fadeIn(600);
// init
var current_month = <?= $init['current_month']; ?>;
var current_year = <?= $init['current_year'] ?>;
// previous, next month ajax call
$(".previous, .next").click(function(event) {
// do stuff to these variables, then ajax call.
$.ajax({
// ajax
});
});
});
In another view, my footer, I have another script block which should use the same variables (current_month and current_year). However, it doesn't know about their existence. What would be the quickest, and easiest, way to pass these variables from the first <script>
block to the other? I can't put the two blocks together because of the way my application is build. Should I just write a function for it which gets and returns these values (and how should I do this? I'm such a newbie) or is there an easier way?
在另一个视图中,我的页脚,我有另一个脚本块,它应该使用相同的变量(current_month 和 current_year)。然而,它并不知道它们的存在。将这些变量从第一个<script>
块传递到另一个块的最快、最简单的方法是什么?由于我的应用程序的构建方式,我无法将这两个块放在一起。我应该为它编写一个函数来获取和返回这些值(我应该怎么做?我是一个新手)还是有更简单的方法?
Thanks a lot!
非常感谢!
回答by JSager
It's really important to learn to namespace your variables in JavaScript. Scope matters, and it matters a lot. Right now because you're using the "var" keyword, your stuff will be in the local scope.
学习在 JavaScript 中命名变量非常重要。范围很重要,而且非常重要。现在因为您正在使用“var”关键字,所以您的内容将在本地范围内。
Some of the other answers here say that you should move them into the global scope. That works, unless something else overwrites them unintentionally. I highly disagree with this approach, globally scoped variables are bad practice in JavaScript.
这里的其他一些答案说你应该将它们移到全局范围内。这是有效的,除非其他东西无意中覆盖了它们。我非常不同意这种方法,全局范围的变量在 JavaScript 中是不好的做法。
Namespacing works like this:
命名空间的工作方式如下:
var foo = foo || {} //Use existing foo or create an empty object.
foo.bar = foo.bar || {}
foo.bar.baz = foo.bar.baz || {}
etc. etc.
等等等等
This may seem like a lot more work, but it also PROTECTS YOUR VARIABLES.
这似乎需要做更多的工作,但它也可以保护您的变量。
You can also add a simple namespacing function that safely namespaces everything against the window object. (I cribbed this from somewhere ages ago, and I think I modified it a little but maybe didn't).
您还可以添加一个简单的命名空间函数,以安全地为 window 对象的所有内容命名。(我很久以前从某个地方抄袭了这个,我想我稍微修改了它,但也许没有)。
Put this at the top of your app and you can namespace stuff with $.namespace("myapp.mydata") and then say myapp.mydata.currentYear = ...
把它放在你的应用程序的顶部,你可以用 $.namespace("myapp.mydata") 命名空间,然后说 myapp.mydata.currentYear = ...
$.namespace = function() {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
d=a[i].split(".");
o=window;
for (j=0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
};
Also, if you're new, or want to get hardcore, I recommend reading JavaScript the Good Parts by Crockford.
另外,如果您是新手,或者想要成为铁杆,我建议您阅读 Crockford 的 JavaScript the Good Parts。
回答by Brad
Declare the variables as global. Just move them outside of the document ready function.
将变量声明为全局变量。只需将它们移到文档就绪功能之外。
var current_month = <?= $init['current_month']; ?>;
var current_year = <?= $init['current_year'] ?>;
$(document).ready(function() {
....
});
current_month
and current_year
can now be accessed from any script block.
current_month
而current_year
现在可以从任何脚本块访问。
回答by Geoff
If you declare your variables outside of any function block, they will be global variables, available to any script on the page.
如果在任何功能块之外声明变量,它们将是全局变量,可用于页面上的任何脚本。
var current_month;
var current_year;
$(document).ready(function () {
// init
current_month = <?= $init['current_month']; ?>;
current_year = <?= $init['current_year'] ?>;
...etc...
});
回答by cweiske
The "var" declaration initializes both variables (current_month
, current_year
) in the ready function scope - thus they are not available elsewhere. You can declare them globally:
"var" 声明在就绪函数范围内初始化两个变量 ( current_month
, current_year
) - 因此它们在其他地方不可用。您可以全局声明它们:
var current_month;
var current_year;
$(document).ready(function() {
...
current_month = ...
}
That way you can use them in the bottom script.
这样你就可以在底部脚本中使用它们。
回答by Eli
Since you var declared these variables inside of a function, they have local scope. Move them outside to make them global:
由于您在函数内部 var 声明了这些变量,因此它们具有局部作用域。将它们移到外面以使其成为全球性的:
// init
var current_month = <?= $init['current_month']; ?>;
var current_year = <?= $init['current_year'] ?>;
$(document).ready(function() {
$("#day_list").fadeIn(600);
// previous, next month ajax call
$(".previous, .next").click(function(event) {
// do stuff to these variables, then ajax call.
$.ajax({
// ajax
});
});
});
The better solution than having global variables is to store them semantically in your HTML, then retrieve them through jQuery:
比使用全局变量更好的解决方案是将它们语义存储在 HTML 中,然后通过 jQuery 检索它们:
<body data-month="<?= $init['current_month']; ?>" data-year="<?= $init['current_year'] ?>">
$(document).ready(function() {
$("#day_list").fadeIn(600);
var current_month = $("body").data("month");
var current_year = $("body").data("year");
// previous, next month ajax call
$(".previous, .next").click(function(event) {
// do stuff to these variables, then ajax call.
$.ajax({
// ajax
});
});
});