访问不同js文件中的变量

Access variable from different js file

本文关键字:变量 文件 js 访问      更新时间:2023-11-30

我有3个html文件&3 js文件

index.html,rank.html,score.html

global.js,rank.js,score.js

在index.html中,我使用iframe包含了rank.html和score.html。

在global.js中,我已经声明了Var-rank&rank.html&score.html.

我正在rank.js中更新rank的值,我想访问score.js中的更新值。在score.jss中,我没有得到更新值。它给出了UNDEFINED值。

我不想在score.html中包含rank.js,所以我创建了global.js&包含在html文件中。

这是我的代码,

Index.html

<html>
    <head>
    </head>
    <body>
<iframe src="../rank/rank.html" frameborder = "0" scrolling="no" width="50%" height = "100%"></iframe>
<iframe src="score.html" frameborder = "0" scrolling="no" width="50%" height = "100%"></iframe>
    </body>
</html> 

global.js

var rank;

score.js

$(document).ready(
        function(){     

                    setInterval(dataupdate, 10000);

    });
function dataupdate() { 
alert(rank) 
};

rank.js

$(document).ready(
            function(){     

                        setInterval(dataupdate, 10000);

        });
    function dataupdate() { 
    rank = "first";
    };

我想在score.js文件中更新排名值如何访问该值。。。

谢谢。。。。。

当您像以前那样声明全局变量时,它会被创建为window对象(即window.rank)的属性。您的主窗口和2个iframe具有独立的window对象,因此从主框架分配的window.rank与从其中一个iframes访问的window.rank不同。

要从iframe内部访问主窗口对象的秩属性,可以使用parent.rank而不是window.rank

如果global.js包含在index.html中,则需要使用window.top.rank(如果index.html也存在于框架中,则使用window.parent.bank)。

您应该在索引中保留变量,因为您只能从iframe 访问父变量

index 
var a=5;
-----------
rank
parent.a=6

现在分数可以读取parent.a作为6

尝试

window.parent.rank

window.top.rank