javascript - 加载新的 html 页面时无法使用 javascript 变量

标签 javascript php html variables

var answers = ['B','B','B','B','B','B'];
var score=0;
var total = answers.length;
function getCheckedValues(radioName) {
  var radios=document.getElementsByName(radioName);
  for(var i=0;i<radios.length;i++) {
    if(radios[i].checked) return radios[i].value;
  }
}

function check_score() {
  for(var i=0;i<total;i++) {
    if(answers[i]==getCheckedValues("question"+i))
      score++;
  }
  returnScore();
}

function returnScore() {
  window.open("score_display.php");
}
window.onload=function congratulations_message() {
  if(score>3)
    document.getElementById('score-display').innerHTML="<h1>Your Score is:</h1><h2>"+score+"</h2>"+"<h1>Congratulations, You are on a path to glory!!!</h1>";
  else {
    document.getElementById('score-display').innerHTML="<h1>Your Score is:</h1><h2>"+score+"</h2>"+"<h1>Oops!!! Hard Luck! Better luck next time</h1>";
  }
}

在上面的代码中,我使用变量 score 来计算问答游戏的分数。当我移动到“score_display.php”,另一个显示“分数”作为祝贺信息的页面时,分数的值变为 0。我假设因为分数是一个全局变量,它可以在我创建的不同 html 文件中使用将我的 javascript 文件链接到。我的假设错了吗?

有什么方法可以保留“score”的值吗?

最佳答案

首先,你不能在页面之间传递 javascript 变量,新页面不在范围之内。查看帖子“ Persist variables between page loads ”。

在这种情况下有很多解决方案可以使用,例如 localStorage、cookies、windows.name...,但我建议一个简单的解决方案,您可以传递 score 变量将 score_display.php 作为参数添加到您的 php 文件中,只需使用 GET 方法,例如:

function check_score() {
    for(var i=0;i<total;i++) {
        if(answers[i]==getCheckedValues("question"+i))
            score++;
    }
    returnScore(score);
}

function returnScore(_score) {
    window.open("score_display.php?score="+_score);
}

然后您可以在另一端(服务器端)使用 $_GET['score'] 在您的 PHP 代码中显示它。

关于javascript - 加载新的 html 页面时无法使用 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51403169/

相关文章:

php - 如何在 javascript 中访问多维 PHP 数组作为 json 编码的变体?

javascript - onclick 函数有时不会触发它的事件

javascript - 一页中的多个窗口用于书签

jquery - 如何查找 LI 是否有 child UL

android - 使用 TalkBack 或 VoiceOver 时样式居中的复选框不可选中

javascript - 动态创建表单并提交

Javascript 警报无法从代码隐藏中运行

php - 如何使用 PHP 和我的 sql 在循环中动态设置图像标签内的值

javascript - Laravel Spark Vue.js 模板中的 @ 符号是什么?

php - json_decode 无法读取以 json 格式存储数据的文本文件