gpt4 book ai didi

javascript - 从不同的js文件访问变量

转载 作者:行者123 更新时间:2023-11-30 18:23:12 25 4
gpt4 key购买 nike

我有 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 等级; & global.js 包含在 rank.html & score.html 中。

我正在更新 rank.js 中的排名值,我想访问 score.js 中的更新值。在 score.js 中,我没有得到更新值它给出了未定义的值。

我不想在 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>

全局.js

var rank;

分数.js

$(document).ready(
function(){


setInterval(dataupdate, 10000);


});
function dataupdate() {

alert(rank)

};

排名.js

$(document).ready(
function(){


setInterval(dataupdate, 10000);


});
function dataupdate() {

rank = "first";

};

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

谢谢.....

最佳答案

当你声明一个全局变量时,它会被创建为 window 对象的属性,即 window.rank。您的主窗口和 2 个 iframe 具有单独的 window 对象,因此从主框架分配的 window.rank 与访问的 window.rank 不同来自其中一个 iframe。

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

关于javascript - 从不同的js文件访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11557139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com