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/