jQuery 在不同的 .js 文件之间传递变量;一个在 iframe 内
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17172634/
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
Pass variables between different .js files; one is inside an iframe
提问by Koiski
I have 2 .js files in the html document like this:
我在 html 文档中有 2 个 .js 文件,如下所示:
<script type="text/javascript" src="js/1.js"></script>
<script type="text/javascript" src="js/2.js"></script>
That document also have an iframe. I have 2 .js in the iframe aswell:
该文档也有一个 iframe。我在 iframe 中也有 2 个 .js:
<script type="text/javascript" src="js/2.js"></script>
<script type="text/javascript" src="js/3.js"></script>
So 2.js is in both documents. My plan was to make that to connect them. I can not put 3.js in both documents because it will mess up stuff.
所以 2.js 在两个文档中。我的计划是将它们连接起来。我不能将 3.js 放在两个文档中,因为它会弄乱东西。
1.js got a variable. I want to use that variable in 3.js. But i can't figure out how to pass a variable from 1.js to 3.js. Is this even possible?
1.js 有一个变量。我想在 3.js 中使用该变量。但我不知道如何将变量从 1.js 传递到 3.js。这甚至可能吗?
*The variable is declared in 1.js.
*该变量在 1.js 中声明。
回答by epascarello
You can not "pass" variables through file references. You would need to add code to pass data from the parent frame to the iframe.
您不能通过文件引用“传递”变量。您需要添加代码以将数据从父框架传递到 iframe。
If the variable is global it is
如果变量是全局变量,则为
//from the iframe
var theVariable = window.parent.yourVaraibleName;
//from the parent
var theVariable = document.getElementById("iframeId").contentWindow.yourVaraibleName;
回答by medzi
Why not using jQuery cookies to pass the variables? Even within the multiple pages. Once you pass the variable you can destroy the cookie.
为什么不使用 jQuery cookie 来传递变量?即使在多个页面内。传递变量后,您就可以销毁 cookie。
回答by Vignesh Subramanian
You cannot pass variables from one js file to the other
Javascript variables are stateless
so they wont be retained.
If you are using .Net then you can make use of Session variables to solve this purpose.
If you use MVC you can go for viewbag or viewdata.
If its a must then declare some variable in the homepage, then assign the value to be passed to the variable in home page and then call the function in 3.js passing this parameter.
您不能将变量从一个 js 文件传递到其他 Javascript 变量,stateless
因此它们不会被保留。如果您使用的是 .Net,那么您可以使用 Session 变量来解决这个问题。如果您使用 MVC,您可以使用 viewbag 或 viewdata。如果必须,则在主页中声明一些变量,然后将要传递给主页中的变量的值赋值,然后通过此参数调用3.js中的函数。
回答by NimChimpsky
jus create a global variable, don't use var keyword
只需创建一个全局变量,不要使用 var 关键字
myGlobal = "probably not a good idea but still";