Pass variables between different .js files; one is

2020-02-12 06:07发布

I have 2 .js files in the html document like this:

    <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:

    <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.

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?

*The variable is declared in 1.js.

4条回答
在下西门庆
2楼-- · 2020-02-12 06:43

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.

查看更多
倾城 Initia
3楼-- · 2020-02-12 06:43

jus create a global variable, don't use var keyword

myGlobal = "probably not a good idea but still";
查看更多
Evening l夕情丶
4楼-- · 2020-02-12 06:48

You can not "pass" variables through file references. You would need to add code to pass data from the parent frame to the 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;
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-02-12 06:54

Why not using jQuery cookies to pass the variables? Even within the multiple pages. Once you pass the variable you can destroy the cookie.

查看更多
登录 后发表回答