变量值在不同文件中使用时会发生变化

Variable value changes when used in different files

本文关键字:变化 文件 变量值      更新时间:2023-09-26

我有一个随机变量,并在一个JavaScript文件中提醒该变量,然后在另一个HTML文件中使用该随机变量的相同值进行一些处理。然而,当我使用alert()函数检查两个文件中的结果时,两个变量在两个文件显示的值似乎不同我想要实现的是让具有相同值的变量在过程中保持一致

在JavaScript文件中,生成随机变量RandomMsg值并警告随机变量Random_Msg:的相关代码

function CreateRandomMsg() {
    var RandomMsg = Msgs_Arr[Math.floor(Math.random()* Msgs_Arr.length)];
    return RandomMsg;
}
var Random_Msg = CreateRandomMsg();
function alertMsg() {
    alert(Random_Msg);
}

在HTML文件中,我包含了这个JavaScript文件,只使用随机变量Random_Msg,但它显示的消息值与JavaScript文件中向用户发出的消息警报不同。我不确定代码的哪一部分包含错误。

Msgs_Arr =["some","messages","here"]
function CreateRandomMsg() {
    var RandomMsg = Msgs_Arr[Math.floor(Math.random()* Msgs_Arr.length)];
    return RandomMsg;
}
var Random_Msg = CreateRandomMsg();
function alertMsg() {
    alert(Random_Msg);
}
alertMsg();
document.getElementById("message").text= Random_Msg;
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body>
    <a id="message"></a>
  </body>
</html>

你想做这样的事吗?请确保您没有调用CreateRandomMsg两次或两次以上