在不同文件

时间:2016-01-14 03:07:12

标签: javascript random

我有一个随机变量并在一个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文件中向用户显示消息警报中显示的不同消息值。我不确定代码的哪一部分包含错误。

1 个答案:

答案 0 :(得分:0)



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>
&#13;
&#13;
&#13;

你正试图这样做吗? 确保您没有两次或更多次调用CreateRandomMsg

相关问题